我正在为网上商店写一个蜘蛛(CrawlSpider)。根据客户需求,我需要编写两个规则:一个用于确定哪些页面有项目,另一个用于提取项目。如何喂蜘蛛蜘蛛爬行内的链接?
我已经独立工作的这两个规则:
- 如果我
start_urls = ["www.example.com/books.php", "www.example.com/movies.php"]
和我评论的Rule
和代码parse_category
,我parse_item
将提取每一个项目。 - 在另一方面,如果
start_urls = "http://www.example.com"
我 发表意见Rule
和parse_item
代码,parse_category
将 返回的每一个环节,其中有一个项目提取,即parse_category
将返回www.example.com/books.php
和www.example.com/movies.php
。
我的问题是,我不知道怎么两个模块合并,使start_urls = "http://www.example.com"
然后parse_category
提取www.example.com/books.php
和www.example.com/movies.php
和饲料这些链接到parse_item
,在那里我居然提取每个项目的信息。
我需要找到一种方法来做到这一点,而不是仅仅使用start_urls = ["www.example.com/books.php", "www.example.com/movies.php"]
,因为如果将来添加了新类别(例如www.example.com/music.php
),蜘蛛将无法自动检测到新类别,应该手动编辑。没什么大不了的,但客户不想要这个。
class StoreSpider (CrawlSpider):
name = "storyder"
allowed_domains = ["example.com"]
start_urls = ["http://www.example.com/"]
#start_urls = ["http://www.example.com/books.php", "http://www.example.com/movies.php"]
rules = (
Rule(LinkExtractor(), follow=True, callback='parse_category'),
Rule(LinkExtractor(), follow=False, callback="parse_item"),
)
def parse_category(self, response):
category = StoreCategory()
# some code for determining whether the current page is a category, or just another stuff
if is a category:
category['name'] = name
category['url'] = response.url
return category
def parse_item(self, response):
item = StoreItem()
# some code for extracting the item's data
return item
'scrapy crawl storyder -o output.json -t json'的输出只是类别列表和其他一些链接,但根本没有任何项目。国际海事组织,它不进入'parse_item'因为检查日志,当它抓取一个项目的链接,它返回名称和URL,这是StoreCategory的字段。 – yzT