我有一个关于如何在scrapy中做这件事的问题。我有一个爬取列出项目页面的蜘蛛。每次找到包含项目的列表页面时,都会调用 parse_item() 回调来提取项目数据并生成项目。到目前为止一切顺利,一切正常。
但是每个项目,除其他数据外,还有一个 url,其中包含有关该项目的更多详细信息。我想跟踪该 url 并将获取的该项目 url 的内容存储在另一个项目字段 (url_contents) 中。
而且我不确定如何组织代码来实现这一点,因为两个链接(列表链接和一个特定的项目链接)的遵循方式不同,回调在不同的时间调用,但我必须在同一个项目处理中关联它们.
到目前为止,我的代码如下所示:
class MySpider(CrawlSpider):
name = "example.com"
allowed_domains = ["example.com"]
start_urls = [
"http://www.example.com/?q=example",
]
rules = (
Rule(SgmlLinkExtractor(allow=('example\.com', 'start='), deny=('sort='), restrict_xpaths = '//div[@class="pagination"]'), callback='parse_item'),
Rule(SgmlLinkExtractor(allow=('item\/detail', )), follow = False),
)
def parse_item(self, response):
main_selector = HtmlXPathSelector(response)
xpath = '//h2[@class="title"]'
sub_selectors = main_selector.select(xpath)
for sel in sub_selectors:
item = ExampleItem()
l = ExampleLoader(item = item, selector = sel)
l.add_xpath('title', 'a[@title]/@title')
......
yield l.load_item()