【问题标题】:AttributeError: 'bytes' object has no attribute 'get'AttributeError:“字节”对象没有属性“获取”
【发布时间】:2020-07-11 05:45:08
【问题描述】:

我正在尝试从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:“字节”对象没有属性“获取” 我需要关于我需要使用什么函数而不是 get() 来提取包含品牌名称的所有 div 元素的建议。 任何帮助表示赞赏。

【问题讨论】:

  • 你有一个 ) 在错误的地方,你可能想在 xpath 上调用 .get() 而不是编码。另外,为什么你首先需要编码,xpath 不接受字符串吗?
  • XPath 不接受 python 3.x 的字符串,参数需要作为字节而不是字符串传递。
  • 对于 OP。有关文档,请参见此处。 docs.scrapy.org/en/latest/topics/…。 UTF-8 编码是 scrapy 的默认编码,JSON 除外。如果您的输出是 JSON,则您已将 FEED_EXPORT_ENCODING 显式设置为 UTF-8。

标签: python-3.x web-scraping scrapy


【解决方案1】:

也许对你有帮助。

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)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-12-29
  • 2020-03-11
  • 2021-09-26
  • 2019-02-02
  • 2021-11-29
  • 2020-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多