【发布时间】:2016-03-09 23:50:27
【问题描述】:
我是 python 和 scrapy 的新手,希望了解其中的方法。 我已经尝试过有关scrapy的官方教程并遵循它,但这只是一个基本示例。我下面描述的要求有所不同,只是稍微复杂一点。
有一个网站显示来自数据库的项目。
对于每个项目,我需要从每个单独的项目页面和搜索结果(列表)页面获取属性。
搜索结果页面 URL 的格式为:
http://example.com/search?&start_index=0
更改 start_index 将更改结果的起始位置。 每个结果页面仅显示 10 条记录。
结果以如下格式显示在表格单元格中:
link | Desc. | Status
我需要检索 Desc。和 Status 属性,然后点击链接到包含更多详细信息的页面,我还将为 Item 检索这些详细信息。
我希望从任何起始索引中检索给定数量的记录。
我目前使用scrapy的方法如下所示(为简洁起见进行了编辑):
import scrapy
from scrapy.exceptions import CloseSpider
from cbury_scrapy.items import MyItem
class ExampleSpider(scrapy.Spider):
name = "example"
allowed_domains = ["example.com"]
start_urls = [
"http://example.com/cgi/search?&start_index=",
]
url_index = 0
URLS_PER_PAGE = 10
records_remaining = 16
crawl_done = False
da = MyItem()
def parse(self, response):
while self.crawl_done != True:
url = "http://example.com/cgi/search?&start_index=" + str(self.url_index)
yield scrapy.Request(url, callback=self.parse_results)
self.url_index += self.URLS_PER_PAGE
def parse_results(self, response):
# Retrieve all table rows from results page
for row in response.xpath('//table/tr[@class="datrack_resultrow_odd" or @class="datrack_resultrow_even"]'):
# extract the Description and Status fields
# extract the link to Item page
url = r.xpath('//td[@class="datrack_danumber_cell"]//@href').extract_first()
yield scrapy.Request(url, callback=self.parse_item)
if self.records_remaining == 0:
self.crawl_done = True
raise CloseSpider('Finished scrape of requested number of records.')
self.records_remaining -= 1
def parse_item(self, response):
# get fields from item page
# ...
yield self.item
当 records_remaining 达到 0 甚至在抛出 CloseSpider 异常之后代码当前不会停止,这是一个错误。
我觉得这源于解析方法的排列方式错误。 以“scrapy”方式构建它的正确方法是什么? 任何帮助表示赞赏。
【问题讨论】:
标签: python scrapy workflow yield