【发布时间】:2014-02-02 15:00:33
【问题描述】:
我想解析 http://en.wikipedia.org/wiki/List_of_circulating_currencies 中的货币表。问题是我没有得到正确格式的输出。我希望输出的形式为:
country currency
在多种货币的情况下,货币应该在下一行或前一个货币之后的空格。这是我能走多远
from bs4 import BeautifulSoup
import urllib2
url="http://en.wikipedia.org/wiki/List_of_circulating_currencies"
soup=BeautifulSoup(urllib2.urlopen(url).read())
i=1
fr=open("out.txt","w")
for row in soup.findAll('table')[0].findAll('tr'):
if i==1:
i+=1
continue
temp_row=row.findAll('td')
print len(temp_row)
"""Handling the case for multiple currencies"""
if(len(temp_row)==5):
ans=row.findAll('td')[0].findAll('a')
if len(ans)==0 :
ans=row.findAll('td')[0].contents
else :
ans=row.findAll('td')[0].findAll('a')[0].contents
fr.write(" "+str(ans)+"\n")
else:
first=row.findAll('td')[0].findAll('a')[0].contents
ans=row.findAll('td')[1].findAll('a')
if len(ans)==0 :
ans=row.findAll('td')[1].contents
else :
ans=row.findAll('td')[1].findAll('a')[0].contents
#print first
fr.write(str(first)+" "+str(ans)+"\n")
问题是当我使用内容[0]而不是它提供的内容时,我想要字符串:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position 15: ordinal not in range(128)
错误我也没有得到精确格式的输出。文件 out.txt 必须由其他一些用 VB 编写的程序读取,所以我希望文件格式尽可能接近指定的格式。另外请帮我清理代码。
更新:
我使用编码得到以下错误:
File "D:/scrap.py", line 33, in <module>
first = first.encode('ascii', 'ignore')
File "C:\Python27\lib\site-packages\bs4\element.py", line 992, in encode
u = self.decode(indent_level, encoding, formatter)
File "C:\Python27\lib\site-packages\bs4\element.py", line 1056, in decode
indent_space = (' ' * (indent_level - 1))
TypeError: unsupported operand type(s) for -: 'str' and 'int'
更新:在开头添加了以下几行以使其正常工作
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
【问题讨论】:
-
我认为我们遗漏了一些东西,在您的代码中某处似乎正在对您的字符串执行数学方程式。
-
当货币名称由两个单词组成时,您如何处理?如
Russian Ruble。对于俄罗斯,输出字符串应该是(根据您的规范)Russia Russian Ruble。读者怎么知道这是一种还是两种货币? csv 文件不是更好的选择吗? -
@SteinarLima 好点看起来我必须将货币代码添加到列表中。但首先我需要正确解析页面。感谢帮助。对于这个问题,您有其他解决方案吗?
-
如果尝试将字符串解码为 ascii,我会遇到与您完全相同的问题。你有什么特别的理由不想要 utf8 吗?
标签: python python-2.7 html-parsing web-scraping beautifulsoup