我使用网络爬虫来获取一些数据。我将数据存储在变量price
中。类型的price
是:Python:将unicode变量转换为字符串变量
<class 'bs4.element.NavigableString'>
的类型的price
每个元素的是:
<type 'unicode'>
基本上price
包含一些空白和换行跟:$520
。我想消除所有额外的符号并只恢复数字520
。我已经做了一个天真的解决方案:
def reducePrice(price):
key=0
string=""
for i in price:
if (key==1):
string=string+i
if (i== '$'):
key=1
key=0
return string
但我想实现一个更优雅的解决方案,改造price
类型为str
,然后使用str
的方法来操作它。我已经在论坛的网页和其他帖子中搜索了很多。最好的我可以得到的是,使用:
p = "".join(price)
我可以生成一个大的unicode变量。如果你能给我一个提示,我会很感激(我在Ubuntu中使用python 2.7)。
编辑添加我的蜘蛛,以防万一你需要它:
def spider(max_pages):
page = 1
while page <= max_pages:
url = "http://www.lider.cl/walmart/catalog/product/productDetails.jsp?cId=CF_Nivel2_000021&productId=PROD_5913&skuId=5913&pId=CF_Nivel1_000004&navAction=jump&navCount=12"
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text)
title = ""
price = ""
for link in soup.findAll('span', {'itemprop': 'name'}):
title = link.string
for link in soup.find('em', {'class': 'oferLowPrice fixPriceOferUp '}):
price = link.string
print(title + '='+ str(reducePrice(price)))
page += 1
spider(1)
编辑2感谢Martin和马苏德我可以用str
方法生成解决方案:
def reducePrice(price):
return int((("".join(("".join(price)).split())).replace("$","")).encode())
该方法返回一个int
。这不是我原来的问题,但这是我项目的下一步。我添加了它,因为我们不能将Unicode转换成int
,但首先使用encode()生成str
。
你试过找bs4来串吗?你很近。 – jamescampbell
我试过'str(price)'然后'price.strip()',但它不起作用。 –
你可以发布你的bs4代码吗?你尝试过str(价格[0])吗? – jamescampbell