下午好,有一个网站的主页上有文章预告 - 这将是解析的起始页。从中,蜘蛛遍历文章页面并收集每篇文章的数据——作者、文章评级、出版日期等。这是我的蜘蛛做得很好。
import scrapy
from scrapy.spiders import Spider
from sxtl.items import SxtlItem
from scrapy.http.request import Request
class SxtlSpider(Spider):
name = "sxtl"
start_urls = ['some_site']
def parse(self, response):
list_of_stories = response.xpath('//div[@id and @class="storyBox"]')
item = SxtlItem()
for i in list_of_stories:
pre_rating = i.xpath('div[@class="storyDetail"]/div[@class="stor\
yDetailWrapper"]/div[@class="block rating_positive"]/span/\
text()').extract()
rating = float(("".join(pre_rating)).replace("+", ""))
link = "".join(i.xpath('div[@class="wrapSLT"]/div[@class="title\
Story"]/a/@href').extract())
if rating > 6:
yield Request("".join(link), meta={'item':item}, callback=\
self.parse_story)
else:
break
def parse_story(self, response):
item = response.meta['item']
number_of_pages = response.xpath('//div[@class="pNavig"]/a[@href]\
[last()-1]/text()').extract()
if number_of_pages:
item['number_of_pages'] = int("".join(number_of_pages))
else:
item['number_of_pages'] = 1
item['date'] = "".join(response.xpath('//span[@class="date"]\
/text()').extract()).strip()
item['author'] = "".join(response.xpath('//a[@class="author"]\
/text()').extract()).strip()
item['text'] = response.xpath('//div[@id="storyText"]/div\
[@itemprop="description"]/text() | //div[@id="storyText"]\
/div[@itemprop="description"]/p/text()').extract()
item['list_of_links'] = response.xpath('//div[@class="pNavig"]\
/a[@href]/@href').extract()
yield item
在这种情况下,一切顺利,但我们只有所有文章的第一页。但是...问题是几乎每篇文章在其他页面上都有续篇,即。有指向文章第 2、3、4、5 页的链接。问题来了。我将 yield item 更改为此:
yield Request("".join(item['list_of_links'][0]), meta={'item':item}, \
callback=self.get_text)
def get_text(self, response):
item = response.meta['item']
item['text'].extend(response.xpath('//div[@id="storyText"]/div\
[@itemprop="description"]/text() | //div[@id="storyText"]\
/div[@itemprop="description"]/p/text()').extract())
yield item
蜘蛛转到文章的下一页,但他已经在随机雕刻第二页了。那些。他可以将第 1 篇文章的第 2 页添加到第 5 篇文章的第 1 页。第3条第2页,附于第9条首页。
请告诉我,如果需要在一个项目中收集的信息位于站点的多个页面上,如何解析站点?(就我而言,如何确保来自不同项目的数据不会相互混合)?
提前致谢。

