Skip to main content
 首页 » 编程设计

python之Scrapy Crawlspider 不爬是正则表达式吗

2024年09月03日25lidabo

我正在尝试导航到每个县,然后从这里导航到每个县的每个城市: http://www.accountant-finder.com/CA/California-accountants.html

我的代码打开上面列出的主页,根据解析器函数抓取标题,但似乎没有应用规则来遵循以“/CA/”开头的县链接(相对路径)(如 CA/Alameda/Alameda_county-California-accountants.html)。

我曾尝试使用各种正则表达式修改规则,但均无济于事。我错过了什么?

import scrapy 
from scrapy.spiders import CrawlSpider,Rule 
from acctfinder.items import Accountant 
from scrapy.linkextractors import LinkExtractor 
 
 
class AccountantSpider(CrawlSpider): 
    name = "Accountant" 
    allowed_domains = ["accountant-finder.com"] 
    start_urls = ["http://www.accountant-finder.com/CA/California-accountants.html"] 
    rules =(Rule(LinkExtractor(allow=('\/CA\/.*',)),callback="parse_item",follow=True),) 
 
    def parse(self,response): 
        item = Accountant() 
        title = response.xpath('//h1/text()')[0].extract() 
        print("title is: "+title) 
        item['title'] = title 
        return item 

请您参考如下方法:

这是使用 CrawlSpider 时的一个常见错误。仔细检查它指定的文档,你 shouldn't be using the parse method .

关于您的蜘蛛的另一件事,该规则指定每个项目都应在 parse_item 方法中处理。所以只需将 parse 方法更改为 parse_item 即可开始工作。