【发布时间】:2016-04-23 08:40:36
【问题描述】:
我无法在 xpath 命令中实现正则表达式。我这里的目标是下载主页的html内容,以及主页上所有超链接的内容。但是,程序会抛出异常,因为某些 href 链接没有连接到任何东西(例如 '//:javascript' 或 '#')。我将如何在 xpath 中使用正则表达式?有没有更简单的方法来排除非绝对的hrefs?
from lxml import html
import requests
main_pg = requests.get("http://gazetaolekma.ru/")
with open("Sample.html","w", encoding='utf-8') as doc:
doc.write(main_pg.text)
tree = html.fromstring(main_pg.content)
hrefs = tree.xpath('//a[re:findall("^(http|https|ftp):.*")]/@href')
for href in hrefs:
link_page = requests.get(href)
with open("%s.html"%href[0:9], "w", encoding ='utf-8') as href_doc:
href_doc.write(link_page.text)
【问题讨论】:
-
您确定可以使用这样的正则表达式吗?我猜你需要一个 XPath
'//a[starts-with(@href, "http:") or starts-with(@href,"https:") or starts-with(@href,"ftp:")]/@href'。 -
我知道您可以在 xpath 中使用正则表达式,但我不完全确定语法以及可以在 xpath 中使用哪些函数。我在发布之前搜索了一段时间,文档非常有限。总之谢谢你!你的答案有效。
-
请检查 har07 的建议。如果您发现该答案也有效,我认为您可以接受该答案。如果没有,我会发布我的解决方法。
-
har07 的解决方案抛出此错误:“所有字符串必须与 XML 兼容:Unicode 或 ASCII,无 NULL 字节或控制字符”
-
好的,但我看到 Casimir 已经发布了一个更接近我的解决方案。
标签: python regex xpath html-parsing