Skip to main content
 首页 » 编程设计

Python CrawlSpider

2025年05月04日8softidea

我一直在学习如何使用 scrapy,尽管我一开始对 python 的经验很少。我开始学习如何使用 BaseSpider 进行抓取。现在我正在尝试抓取网站,但我遇到了一个让我很困惑的问题。这是来自官方网站的示例代码 http://doc.scrapy.org/topics/spiders.html .

from scrapy.contrib.spiders import CrawlSpider, Rule 
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor 
from scrapy.selector import HtmlXPathSelector 
from scrapy.item import Item 
 
class MySpider(CrawlSpider): 
    name = 'example.com' 
    allowed_domains = ['example.com'] 
    start_urls = ['http://www.example.com'] 
 
    rules = ( 
        # Extract links matching 'category.php' (but not matching 'subsection.php') 
        # and follow links from them (since no callback means follow=True by     default). 
        Rule(SgmlLinkExtractor(allow=('category\.php', ), deny=('subsection\.php',     ))), 
 
        # Extract links matching 'item.php' and parse them with the spider's method     parse_item 
        Rule(SgmlLinkExtractor(allow=('item\.php', )), callback='parse_item'),) 
 
    def parse_item(self, response): 
        print "WHY WONT YOU WORK!!!!!!!!" 
        self.log('Hi, this is an item page! %s' % response.url) 
 
        hxs = HtmlXPathSelector(response) 
        item = TestItem() 
        item['id'] = hxs.select('//td[@id="item_id"]/text()').re(r'ID: (\d+)') 
        item['name'] = hxs.select('//td[@id="item_name"]/text()').extract() 
        item['description'] =     hxs.select('//td[@id="item_description"]/text()').extract() 
        return item 

我所做的唯一更改是声明:

print "WHY WONT YOU WORK!!!!!!!!" 

但是由于我在运行时没有看到这个打印语句,我担心这个函数没有被调用。这是我直接从官方scrapy网站上拿来的代码。我做错了什么或误解了什么?

请您参考如下方法:

start_urls = ['http://www.example.com'] 

example.com 没有任何类别或项目的链接。这只是抓取的网站 URL 可能是什么的示例。

这是文档中的一个无效示例。