我正在尝试使用XPATH从网站获取所有链接,URL格式非常具体但动态。
我想获取的URL的格式为“ / static_word /带破折号的随机字符串/ random_number”(3段:第1个静态,第2个随机字符串,第3个随机数)。你们可以帮我实现这一目标吗?
我试图用正则表达式来做,但是没有用。
这是我的代码:
from lxml import html
import ssl
import requests
ssl._create_default_https_context = ssl._create_unverified_context
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
myRequest = requests.get("https://somesecureurl.com/", headers=headers)
webpage = html.fromstring(myRequest.content)
theLinks = webpage.xpath("//a[contains(@href,'^/static_word/[A-Za-z0-9_-]/[0-9]$')]")
print(theLinks)
最佳答案
有一个matches(),您可以使用它通过正则表达式来匹配所需的字符串:
//a[matches(@href,'^/static_word/[A-Za-z0-9_-]+/[0-9]+$')]
但是AFAIK
lxml
不支持XPath 2.0功能您可以尝试以下一种方法:
//a[starts-with(@href, '/static_word/') and
(string-length(@href)-string-length(translate(@href, '/', '')))=3 and
number(substring-after(substring-after(@href, '/static_word/'), '/'))>=0]
以上谓词应匹配:
starts-with(@href, "/static_word/")
-a
节点,其中@href
以子字符串'/static_word/'
开头(string-length(@href)-string-length(translate(@href, '/', '')))=3
-同样@href
恰好包含3个斜杠number(substring-after(substring-after(@href, '/static_word/'), '/'))>=0
-最后一个子字符串是任何正数这看起来很糟糕,但应该可以工作:)