Scrapy SgmlLinkExtractor忽略了允许的链接
请看看Scrapy文档中的这个爬虫示例。它的解释是:
这个爬虫会从example.com的主页开始爬取,收集分类链接和商品链接,并用parse_item方法解析后者。对于每个商品的响应,它会使用XPath从HTML中提取一些数据,然后用这些数据填充一个Item。
我完全复制了这个爬虫,并把“example.com”换成了另一个初始网址。
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy.item import Item
from stb.items import StbItem
class StbSpider(CrawlSpider):
domain_name = "stb"
start_urls = ['http://www.stblaw.com/bios/MAlpuche.htm']
rules = (Rule(SgmlLinkExtractor(allow=(r'/bios/.\w+\.htm', )), callback='parse', follow=True), )
def parse(self, response):
hxs = HtmlXPathSelector(response)
item = StbItem()
item['JD'] = hxs.select('//td[@class="bodycopysmall"]').re('\d\d\d\d\sJ.D.')
return item
SPIDER = StbSpider()
但是我的爬虫“stb”并没有像预期那样从“/bios/”收集链接。它运行初始网址,抓取item['JD']
并把它写入文件,然后就结束了。
为什么SgmlLinkExtractor
被忽略了呢?Rule
是被读取的,因为它会捕捉到Rule
行中的语法错误。
这是个bug吗?我的代码有什么问题吗?除了每次运行时看到的一堆未处理的错误外,没有其他错误。
我想知道我在这里做错了什么。谢谢任何线索。我是不是误解了SgmlLinkExtractor
的作用?
1 个回答
11
parse
这个函数其实是在CrawlSpider类里面实现并使用的,而你不小心把它覆盖掉了。如果你把这个名字改成别的,比如parse_item
,那么规则就应该能正常工作了。