如何使用 lxml 从 html 锚中提取 href url?
How to extract href url from html anchor using lxml?
我尝试使用 lxml 提取下一页 href 字符串。
例如,我尝试从以下示例中的 html 中提取“/review/bulb.co.uk?b=MTYxOTg5MDE1OTAwMHw2MDhkOGZlZmY5ZjQ4NzA4ZTA4MWI2Mzk”:
<nav rel="nav" class="pagination-container AjaxPager">
<a href="/review/bulb.co.uk?b=MTYxOTg5MDE1OTAwMHw2MDhkOGZlZmY5ZjQ4NzA4ZTA4MWI2Mzk" data-page-number="next-page" class="button button--primary next-page" rel="next" data-track-link="{'target': 'Company profile', 'name': 'navigation', 'navigationType': 'next'}">
Next page
</a>
</nav>
我尝试了以下方法,但它 returns 不是我要查找的字符串的列表:
import requests
import lxml.html as html
URL = https://uk.trustpilot.com/review/bulb.co.uk
page = requests.get(URL)
tree = html.fromstring(page.content)
href = tree.xpath('//a/@href')
知道我做错了什么吗?
对您的代码进行此更改
href = tree.xpath('//a[@class="button button--primary next-page"]/@href')
href[0]
给我这个输出:
'/review/bulb.co.uk?b=MTYxOTk1ODMxMzAwMHw2MDhlOWEyOWY5ZjQ4NzA4ZTA4MjMxNTE'
接近你问题的输出(它的值可能会动态变化)。
我尝试使用 lxml 提取下一页 href 字符串。
例如,我尝试从以下示例中的 html 中提取“/review/bulb.co.uk?b=MTYxOTg5MDE1OTAwMHw2MDhkOGZlZmY5ZjQ4NzA4ZTA4MWI2Mzk”:
<nav rel="nav" class="pagination-container AjaxPager">
<a href="/review/bulb.co.uk?b=MTYxOTg5MDE1OTAwMHw2MDhkOGZlZmY5ZjQ4NzA4ZTA4MWI2Mzk" data-page-number="next-page" class="button button--primary next-page" rel="next" data-track-link="{'target': 'Company profile', 'name': 'navigation', 'navigationType': 'next'}">
Next page
</a>
</nav>
我尝试了以下方法,但它 returns 不是我要查找的字符串的列表:
import requests
import lxml.html as html
URL = https://uk.trustpilot.com/review/bulb.co.uk
page = requests.get(URL)
tree = html.fromstring(page.content)
href = tree.xpath('//a/@href')
知道我做错了什么吗?
对您的代码进行此更改
href = tree.xpath('//a[@class="button button--primary next-page"]/@href')
href[0]
给我这个输出:
'/review/bulb.co.uk?b=MTYxOTk1ODMxMzAwMHw2MDhlOWEyOWY5ZjQ4NzA4ZTA4MjMxNTE'
接近你问题的输出(它的值可能会动态变化)。