如何从本身就是超链接的href中获取URL?

2024-09-30 19:21:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python和lxml来尝试刮取this html page。我遇到的问题是试图从这个超链接文本“Chapter02a”中获取URL。(请注意,我似乎无法使链接格式在这里工作)。你知道吗

<li><a href="[Chapter02A](https://www.math.wisc.edu/~mstemper2/Math/Pinter/Chapter02A)">Examples of Operations</a></li>

我试过了

//ol[@id="ProbList"]/li/a/@href

但那只给了我文本“第02a章”。你知道吗

此外:

//ol[@id="ProbList"]/li/a

返回一个lxml.html.HtmlElement文件'对象,而我在文档中找到的任何属性都不能完成我正在尝试的操作。你知道吗

from lxml import html
import requests

chapter_req = requests.get('https://www.math.wisc.edu/~mstemper2/Math/Pinter/Chapter02')
chapter_html = html.fromstring(chapter_req.content)
sections = chapter_html.xpath('//ol[@id="ProbList"]/li/a/@href')
print(sections[0])

我希望是指向子节的URL列表。你知道吗


Tags: https文本idurlhtmlwwwmathli
2条回答

您还可以直接在XPATH级别进行连接,从相对链接重新生成URL:

from lxml import html
import requests

chapter_req = requests.get('https://www.math.wisc.edu/~mstemper2/Math/Pinter/Chapter02')
chapter_html = html.fromstring(chapter_req.content)
sections = chapter_html.xpath('concat("https://www.math.wisc.edu/~mstemper2/Math/Pinter/",//ol[@id="ProbList"]/li/a/@href)')
print(sections)

输出:

https://www.math.wisc.edu/~mstemper2/Math/Pinter/Chapter02A

您看到的返回是正确的,因为Chapter02a是指向下一节的“相对”链接。完整的url没有列出,因为它不是以这种方式存储在html中的。你知道吗

要获取可使用的完整URL,请执行以下操作:

url_base = 'https://www.math.wisc.edu/~mstemper2/Math/Pinter/'
sections = chapter_html.xpath('//ol[@id="ProbList"]/li/a/@href')
section_urls = [url_base + s for s in sections]

相关问题 更多 >