无法使用Python beautifulsoup从不需要的字符中清除字符串
当我运行以下命令时无法使用Python beautifulsoup从不需要的字符中清除字符串,python,python-3.x,web-scraping,beautifulsoup,Python,Python 3.x,Web Scraping,Beautifulsoup,当我运行以下命令时 prices = [price.text.strip() for price in soup.select('.special-price')] prices = prices.replace(u'\xa0', u' ') print(prices) 我得到的“列表”对象没有属性“替换” 我应该把它放在哪里?有什么方法可以一步清除它吗 谢谢您是的,因为您创建了具有列表理解功能的列表 您需要通过prices=''将列表转换为字符串。如果不将其解析为字符串,则加入(prices
prices = [price.text.strip() for price in soup.select('.special-price')]
prices = prices.replace(u'\xa0', u' ')
print(prices)
我得到的“列表”对象没有属性“替换”
我应该把它放在哪里?有什么方法可以一步清除它吗
谢谢您是的,因为您创建了具有列表理解功能的列表
您需要通过
prices=''将列表转换为字符串。如果不将其解析为字符串,则加入(prices)
假设价格是字符串列表。那么价格将是一个字符串。现在你可以在上面调用replace了 由于我们无法访问您的样本数据,因此应该:
您需要将replace()
放在str
而不是列表上,例如:
prices = ['1','1','2','3','4','5','1','1','1']
print([x.replace('1', '9') for x in prices])
输出:
['9', '9', '2', '3', '4', '5', '9', '9', '9']
因为“list”对象没有属性“replace”
。这就是为什么
你试图单独改变价格。字符串有replace
方法,但列表没有
您应该将替换添加到列表中
prices = [price.text.strip().replace(u'\xa0', u' ') for price in soup.select('.special-price')]
print(prices)
因为'list'对象没有'replace'属性@Dirty显然是,但是。。在哪里以及如何使用?尝试了prices=[price.replace(u'\xa0',u'')以获取价格中的价格]
?然后从一开始就开始执行:prices=[price.text.strip()。将(u'\xa0',u'')替换为汤中的价格。选择('.special price')]
。虽然我不确定你为什么会出现这个错误。所有的.text
和.strip
和.replace
方法都会在每次迭代中执行。优先级与写入的优先级相同-首先是.text
,然后是.strip
,然后是。replace
。