[英]how to remove first characters of an item within array in python scrapy
[英]Replacing characters in Scrapy item
我正在尝试使用 Scrapy 从一个商业网站上抓取数据。 对于价格标签,我想删除“$”,但我当前的代码不起作用。
def parse(self, response):
for sel in response.xpath('//section[@class="items-box"]'):
item = ShopItem()
item['name'] = sel.xpath('a/div/h3/text()').extract()
item['price'] = sel.xpath('a/div/div/div[1]/text()').extract().replace("$", "")
yield item
AttributeError: 'list' object has no attribute 'replace'
使用 Scrapy 时删除字符的适当方法是什么?
extract()
会返回一个list ,你可以使用extract_first()
来获取单个值:
item['price'] = sel.xpath('a/div/div/div[1]/text()').extract_first().replace("$", "")
或者,您可以使用.re()
方法,例如:
item['price'] = sel.xpath('a/div/div/div[1]/text()').re(r"\$(.*?)")
您可以先使用join()
然后使用replace()
将列表转换为字符串并将"$"
替换"$"
""
示例:
prices = ''.join(price)
if '$' in prices:
prices = prices.replace("$", "")
希望它有帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.