问题描述
我正在尝试运行间谍程序来提取房地产广告信息。
我的代码:
import scrapy
from ..items import RealestateItem
class AddSpider (scrapy.Spider):
name = 'Add'
start_urls = ['https://www.exampleurl.com/2-bedroom-apartment-downtown-4154251/']
def parse(self,response):
items = RealestateItem()
whole_page = response.css('body')
for item in whole_page:
Title = response.css(".obj-header-text::text").extract()
items['Title'] = Title
yield items
在控制台中运行后:
scrapy crawl Add -o Data.csv
在.csv文件中,我得到
['\n 2-bedroom-apartment ']
Title = response.css(".obj-header-text::text").extract().strip()
但是可怜的回报:
Title = response.css(".obj-header-text::text").extract().strip()
AttributeError: 'list' object has no attribute 'strip'
2-bedroom-apartment
解决方法
AttributeError: 'list' object has no attribute 'strip'
出现此错误是因为.extract()
返回了一个列表,而.strip()
是一种字符串方法。
如果该选择器始终返回一个项目,则可以用.get()
[或extract_first()
]代替.extract()
来代替它,这将返回一个字符串第一项,而不是列表。了解更多here。
如果需要它来返回列表,则可以遍历列表,在每个项目中调用strip,例如:
title = response.css(".obj-header-text::text").extract()
title = [item.strip() for item in title]
您还可以使用XPath选择器而不是CSS选择器,这样就可以使用normalize-space剥离whitespace。
title = response.xpath('normalize-space(.//*[@class="obj-header-text"]/text())').extract()
此XPath可能需要一些调整,因为您没有发布我无法检查的源文件