首页 > 解决方案 > AttributeError:“字节”对象没有属性“获取”

问题描述

我正在尝试从https://www.gizbot.com/mobile-brands-in-india/中提取所有品牌名称。下面是 mobiles_spiders.py 文件的代码

class MobilesSpider(scrapy.Spider):
    name = "mobiles"

    def start_requests(self):
        urls = [
            'https://www.gizbot.com/mobile-brands-in-india/',
           
        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        page = response.url.split("/")[-2]
        filename = 'mobiles-%s.html' % page
        with open(filename, 'wb') as f:
            f.write(response.xpath(str.encode('.//div[has-class("all-brands-block-desc-brand")]/text()').get()))
        self.log('Saved file %s' % filename)

但是代码给了我错误,因为 AttributeError: 'bytes' 对象没有属性 'get' 我需要关于我需要使用什么函数而不是 get() 来提取包含品牌名称的所有 div 元素的建议。任何帮助表示赞赏。

标签: python-3.xweb-scrapingscrapy

解决方案


它可能会帮助你。

import scrapy
    
class MobilesSpider(scrapy.Spider):
    name = "mobiles"

    def start_requests(self):
        urls = [
            'https://www.gizbot.com/mobile-brands-in-india/',

        ]
        for url in urls:
            yield scrapy.Request(url=url, callback=self.parse)

    def parse(self, response):
        page = response.url.split("/")[-2]
        filename = 'mobiles-%s.html' % page
        with open(filename, 'wb') as f:
            f.write(response.xpath('.//div[has-class("all-brands-block-desc-brand")]/text()').get().encode('utf-8'))
        self.log('Saved file %s' % filename)

推荐阅读