Scrapy爬虫set对象getall报错及ozellikler仅返回单条数据问题
解决Scrapy爬虫的两个问题
问题1:AttributeError: 'set' object has no attribute 'getall'
这个错误说明你代码里的set_box变量是Python内置的集合(set),而非Scrapy的Selector对象——只有Selector对象才具备getall()方法。
检查代码,大概率是你不小心把set_box定义成了集合(比如写了set_box = set()),或是赋值时误用了集合推导式。你需要确保set_box是通过Scrapy的response.xpath()或response.css()获取的Selector列表,示例:
# 正确获取Selector对象 set_box = response.xpath('//div[@class="feature-container"]') # 调用getall()提取所有文本内容 feature_list = set_box.xpath('./text()').getall()
问题2:ozellikler字段仅返回最后一条数据
这是因为你在收集特征数据时,每次循环都直接给ozellikler赋值,覆盖了之前的内容,而非往列表中追加数据。
修改思路:
- 先初始化一个空列表用于存储所有特征
- 遍历每个特征元素时,将提取到的内容追加到列表
- 最后把完整列表赋值给
ozellikler字段
示例代码:
def parse_inner_page(self, response): # 初始化空列表 ozellikler = [] # 遍历所有特征节点 for feature_item in response.xpath('//div[@class="feature-item"]'): feature_content = feature_item.xpath('./text()').get().strip() # 追加到列表,而非直接赋值覆盖 ozellikler.append(feature_content) # 返回包含完整特征列表的Item yield { 'ozellikler': ozellikler, # 其他字段... }
如果你的特征是键值对形式(比如"屏幕尺寸: 6.7英寸"),可调整为字典收集:
ozellikler = {} for feature_row in response.xpath('//div[@class="feature-row"]'): key = feature_row.xpath('./span[@class="key"]/text()').get().strip() value = feature_row.xpath('./span[@class="value"]/text()').get().strip() ozellikler[key] = value
内容的提问来源于stack exchange,提问作者6wom9
相关产品推荐
相关产品推荐

