Python - 抓取 IMDb 网站时出现 XPath 问题



我正在尝试使用Python抓取IMDb上的电影,我可以获取有关除演员姓名之外的所有重要方面的数据。

这是我正在处理的示例 URL:

https://www.imdb.com/title/tt0106464/

使用"检查"浏览器功能,我找到了与所有参与者名称相关的XPath,但是当涉及到在Python上运行代码时,看起来XPath无效(不返回任何内容(。

这是我正在使用的代码的简单版本:

import requests
from lxml import html
movie_to_scrape = "https://www.imdb.com/title/tt0106464"
timeout_time = 5
IMDb_html = requests.get(movie_to_scrape, timeout=timeout_time)
doc = html.fromstring(IMDb_html.text)
actors = doc.xpath('//table[@class="cast_list"]//tbody//tr//td[not(contains(@class,"primary_photo"))]//a/text()')
print(actors)

我尝试多次更改 XPath,试图使其更通用,然后更具体,但它仍然没有返回任何内容

不要盲目接受使用inspect element看到的标记结构。
浏览器非常宽松,会尝试修复源代码中的任何标记问题。
话虽如此,如果您使用view source检查源,您可以看到您要抓取的表没有<tbody>,因为它们是由浏览器插入的。
因此,如果您在此处将其删除//table[@class="cast_list"]//tbody//tr//td[not(contains(@class,"primary_photo"))]//a/text()->//table[@class="cast_list"]//tr//td[not(contains(@class,"primary_photo"))]//a/text()
您的查询应该可以工作。

从查看 HTML 开始,从一个简单的 xpath 开始,例如//td[@class="primary_photo"]

<table class="cast_list">    
<tr><td colspan="4" class="castlist_label">Cast overview, first billed only:</td></tr>
<tr class="odd">
<td class="primary_photo">
<a href="/name/nm0000418/?ref_=tt_cl_i1"
><img height="44" width="32" alt="Danny Glover" title="Danny Glover" src="https://m.media-amazon.com/images/G/01/imdb/images/nopicture/32x44/name-2138558783._CB470041625_.png" class="loadlate hidden " loadlate="https://m.media-amazon.com/images/M/MV5BMTI4ODM2MzQwN15BMl5BanBnXkFtZTcwMjY2OTI5MQ@@._V1_UY44_CR1,0,32,44_AL_.jpg" /></a>          </td>
<td>

蟒:

for photo in doc.xpath('//td[@class="primary_photo"]'):
print photo

最新更新