【发布时间】: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