[英]wrong Xpath in IMDB spider scrapy
在這里: IMDB scrapy獲取所有電影數據
response.xpath( “// * [@類= '結果'] / TR / TD [3]”)
返回空列表。 我試圖將其更改為:
response.xpath(“ // * [包含(@class,'圖表全角')] / tbody / tr”)
沒有成功。
有什么幫助嗎? 謝謝。
我沒有時間去仔細研究IMDB來徹底獲取所有電影數據 ,但要點是。 問題語句是從給定站點獲取所有電影數據。 它涉及兩件事。 首先是瀏覽包含該年所有電影列表的所有頁面。 第二個是獲取每個電影的鏈接,然后在這里您自己做魔術。
您面臨的問題是獲取每個電影的鏈接的xpath。 這很可能是由於網站結構的變化(我沒有時間來驗證可能的差異)。 無論如何,以下是您需要的xpath
。
首先:
我們將div
類nav
作為地標,並在其子級中找到lister-page-next next-page
。
response.xpath("//div[@class='nav']/div/a[@class='lister-page-next next-page']/@href").extract_first()
這將給出: 指向下一頁的鏈接 | 如果在最后一頁 ,則返回None
(因為不存在下一頁標簽)
第二:
這是OP最初的懷疑。
#Get the list of the container having the title, etc
list = response.xpath("//div[@class='lister-item-content']")
#From the container extract the required links
paths = list.xpath("h3[@class='lister-item-header']/a/@href").extract()
現在,您需要做的就是遍歷每個paths
元素並請求頁面。
感謝您的回答。 我最終像這樣使用了xPath:
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from crawler.items import MovieItem
IMDB_URL = "http://imdb.com"
class IMDBSpider(CrawlSpider):
name = 'imdb'
# in order to move the next page
rules = (Rule(LinkExtractor(allow=(), restrict_xpaths=("//div[@class='nav']/div/a[@class='lister-page-next next-page']",)),
callback="parse_page", follow= True),)
def __init__(self, start=None, end=None, *args, **kwargs):
super(IMDBSpider, self).__init__(*args, **kwargs)
self.start_year = int(start) if start else 1874
self.end_year = int(end) if end else 2017
# generate start_urls dynamically
def start_requests(self):
for year in range(self.start_year, self.end_year+1):
# movies are sorted by number of votes
yield scrapy.Request('http://www.imdb.com/search/title?year={year},{year}&title_type=feature&sort=num_votes,desc'.format(year=year))
def parse_page(self, response):
content = response.xpath("//div[@class='lister-item-content']")
paths = content.xpath("h3[@class='lister-item-header']/a/@href").extract() # list of paths of movies in the current page
# all movies in this page
for path in paths:
item = MovieItem()
item['MainPageUrl'] = IMDB_URL + path
request = scrapy.Request(item['MainPageUrl'], callback=self.parse_movie_details)
request.meta['item'] = item
yield request
# make sure that the start_urls are parsed as well
parse_start_url = parse_page
def parse_movie_details(self, response):
pass # lots of parsing....
使用scrapy crawl imdb -a start=<start-year> -a end=<end-year>
運行它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.