【发布时间】:2015-06-02 02:15:25
【问题描述】:
我使用网络爬虫来获取一些数据。我将数据存储在变量price 中。 price 的类型为:
<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)
edit 2感谢 Martin 和 mASOUD,我可以使用 str 方法生成解决方案:
def reducePrice(price):
return int((("".join(("".join(price)).split())).replace("$","")).encode())
这个方法返回一个int。这不是我最初的问题,但它是我项目的下一步。我添加它是因为我们无法将 unicode 转换为 int,但我们可以先使用 encode() 生成 str。
【问题讨论】:
-
您是否尝试过寻找 bs4 到字符串?你很接近。
-
我尝试了
str(price),然后尝试了price.strip(),但没有成功。 -
你能发布你的bs4代码吗?你试过 str(price[0]) 吗?
标签: python unicode casting web-crawler unicode-string