python - 将 BeautifulSoup 中的文本写入文件

标签 python python-2.7 html-parsing web-scraping beautifulsoup

我想解析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")

最佳答案

如果您同意文件中的 utf 字符,则可以使用 encode('utf8') 将 unicode 对象转换为 utf 编码字符串。

关于python - 将 BeautifulSoup 中的文本写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21115456/

相关文章:

python - 使用 matplotlib 求解多边形中的点

python - 检查成员变量是否由构造函数初始化?

python - 在 python 中使用德摩根定律有什么好处吗?

python - 使用 find 方法查找完全匹配

python - 在我的 Raspberry PI 上使用 Python 和 OpenCV 没有保存视频文件

java - HTML 页面加载并在 .txt 文件中显示

python - BS4 : removing <a> tags

python - Django 将项目路径存储在哪里?

python - 在Python中使用负数对字符串进行切片时,0被禁用?

java - 如何在android中为jsoup设置用户代理和连接超时