簡體   English   中英

Python-刮IMDb網站時出現XPath問題

[英]Python - XPath issue while scraping the IMDb Website

我正在嘗試使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM