【发布时间】:2017-04-16 11:48:13
【问题描述】:
我有一个网站要抓取。在主页上它有故事预告 - 所以,这个页面将是我们的开始解析页面。我的蜘蛛会从它那里收集有关每个故事的数据——作者、评级、出版日期等。这些都是由蜘蛛正确完成的。
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
因此,数据收集正确,但我们只有每个故事的第一页。但是每个 sory 都有几页(并且有指向第 2、3、4 页的链接,有时是 15 页)。这就是问题出现的地方。我用这个替换产量项目:(获取每个故事的第二页)
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
Spider 收集下一页(第 2 页),但它会将它们连接到任何故事的第一页。例如,第 1 层的第 2 页可以添加到第 4 层。第 5 故事的第 2 页被添加到第 1 故事。以此类推。
请帮忙,如果要抓取的数据分布在多个网页上,如何将数据收集到一个项目(一个字典)中? (在这种情况下 - 如何不让来自不同项目的数据相互混合?)
谢谢。
【问题讨论】:
-
你查看过这个链接吗:stackoverflow.com/questions/13910357/… ?
-
@Wandrille 我已经找到了解决方案,但感谢您提供有趣的链接。
标签: python web-scraping scrapy