无法使用Python beautifulsoup清除不需要的字符串

问题描述 投票:0回答:3

当我运行以下

prices = [price.text.strip() for price in soup.select('.special-price')]
prices = prices.replace(u'\xa0', u' ')
print(prices)

我得到'list'对象没有属性'replace'

我应该把替换放在哪里?有什么方法可以一步清除它吗?

谢谢

python python-3.x web-scraping beautifulsoup
3个回答
0
投票

因为'list' object has no attribute 'replace'。这就是为什么。

你试图单独改变价格。字符串有replace方法,但列表没有。

您应该为列表理解添加替换。

prices = [price.text.strip().replace(u'\xa0', u' ') for price in soup.select('.special-price')]
print(prices)

1
投票

是的,因为您创建了一个包含列表推导的列表

您需要通过prices=''.join(prices)将列表转换为字符串,假设价格是字符串列表,如果不将其解析为字符串。价格将是一个字符串。现在你可以调用替换它。


1
投票

由于我们无法访问您的示例数据,因此应执行以下操作:

你需要把replace()放在str而不是list,喜欢:

prices = ['1','1','2','3','4','5','1','1','1']
print([x.replace('1', '9') for x in prices])

OUTPUT:

['9', '9', '2', '3', '4', '5', '9', '9', '9']
© www.soinside.com 2019 - 2024. All rights reserved.