python-3.x - 在抓取页面时使用多个解析器
问题描述
我已经搜索了有关此主题的一些问题,但找不到解决问题的方法。
我目前正在尝试根据我要搜索的产品在网站上使用多个解析器。在尝试了一些方法后,我最终得到了这个:
有了这个启动请求:
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 之上,但我仍然得到同样的错误。
解决方案
您需要引用方法而不是函数,因此只需像这样更改它:
yield response.follow(urlProducto, callback = self.parse_laptop)
推荐阅读
- swift - GraphQL Apollo iOS 14 上传失败
- pentaho - 使用带有 Pentaho CE 的 node js 执行 Pentaho 转换(ktr)
- javascript - 在引导程序中创建一个透明的导航栏以在 Gatsby JS 应用程序中使用
- flutter - 您必须宽 80 到 300 像素,高 30 到 85 像素
- oracle - 从右侧获取子字符串
- amazon-web-services - 建议:将 Amazon Cognito 与 AWS DynamoDB 集成
- sql - 在多个子组上运行选择
- ios - iOS 图表 | 在折线图视图中随机获取橙色/棕色轴线
- vue.js - Vue.js 在运行时动态扩展/替换子组件方法并访问父范围
- css - CSS:将字体图标代码存储在 CSS 变量中