【发布时间】:2015-03-14 18:19:40
【问题描述】:
我正在寻找从
获取 href 的 xpath<a class="a-link-normal s-access-detail-page a-text-normal" title="Nikon Coolpix L330 - 20.2 MP Digital Camera with 26x zoom 35mm NIKKOR VR lens and FULL HD 720p (Black)" href="https://rads.stackoverflow.com/amzn/click/com/B00HQDBLDO" rel="nofollow noreferrer"><h2 class="a-size-base s-inline s-access-title a-text-normal">Nikon Coolpix L330 - 20.2 MP Digital Camera with 26x zoom 35mm NIKKOR VR lens and FULL HD 720p (Black)</h2></a>
我尝试了以下代码:
url = "http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=digital+camera&rh=i%3Aaps%2Ck%3Adigital+camera"
page = requests.get(url)
tree = html.fromstring(page.text)
hrefs = tree.xpath('//*/a/@href')
for href in hrefs:
if "keywords=digital+camera" in href:
print href
这里没有打印任何内容。
我不确定 xpath 是否可以做到这一点?这是链接:http://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=digital+camera
【问题讨论】:
-
有多种方法可以通过 xpath 访问它。由于我们没有看到完整的 HTML 代码(或链接),我们不知道表达式的可靠性。另外,为什么这个问题用 Python 标记?
-
@alecxe 问题已更新。谢谢
-
谢谢。你有什么输入?我的意思是,链接标题是你可以依赖的?
-
是的。链接是输入。我想获得像amazon.com/dp/B00HQDBLDO 这样的每个href。
-
@Tomalak 我在这里更新了我的代码。请建议。
标签: python html xpath html-parsing lxml