我正在爲網上商店寫一個蜘蛛(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