首页 > 解决方案 > 在抓取页面时使用多个解析器

问题描述

我已经搜索了有关此主题的一些问题,但找不到解决问题的方法。

我目前正在尝试根据我要搜索的产品在网站上使用多个解析器。在尝试了一些方法后,我最终得到了这个:

有了这个启动请求:

def start_requests(self):

    txtfile = open('productosABuscar.txt', 'r')

    keywords = txtfile.readlines()

    txtfile.close()

    for keyword in keywords:

        yield Request(self.search_url.format(keyword))

这进入了我的正常 parse_item。

我想要做的是,使用这个 parse_item(通过检查笔记本电脑、平板电脑等项目类别):

def parse_item(self,response):
        #I get the items category for the if/else
    category = re.sub('Back to search results for |"','', response.xpath('normalize-space(//span[contains(@class, "a-list-item")]//a/text())').extract_first())
        #Get the product link, for example (https://www.amazon.com/Lenovo-T430s-Performance-Professional-Refurbished/dp/B07L4FR92R/ref=sr_1_7?s=pc&ie=UTF8&qid=1545829464&sr=1-7&keywords=laptop)
    urlProducto = response.request.url

        #This can be done in a nicer way, just trying out if it works atm
    if category == 'Laptop':

        yield response.follow(urlProducto, callback = parse_laptop)

和:

def parse_laptop(self, response):

    #Parse things

有什么建议么?运行此代码时出现的错误是未定义“parse_laptop”。我已经尝试将 parse_laptop 放在 parse_item 之上,但我仍然得到同样的错误。

标签: python-3.xweb-scrapingscrapy

解决方案


您需要引用方法而不是函数,因此只需像这样更改它:

yield response.follow(urlProducto, callback = self.parse_laptop)

推荐阅读