【问题标题】:How do I save text from website using beautifulsoup to .txt file?如何使用 beautifulsoup 将网站中的文本保存到 .txt 文件?
【发布时间】:2014-08-05 07:46:51
【问题描述】:

我是 python 和网络抓取的新手。我遇到了一个问题,我似乎不知道如何解决它。

我正在尝试从网站复制文本,当我将所有内容打印到终端时,它会弹出正常。

问题是当我尝试将其保存到文本文件时。我收到此错误:

     Traceback (most recent call last):
     File "t3.py", line 43, in <module>
     Case_info.write(item.text+"\n")
     UnicodeEncodeError: 'ascii' codec can't encode characters in position 16-17: ordinal not in range(128)

我不确定如何解决它。我在这个特定部分的代码如下:

import mechanize
import requests
from bs4 import BeautifulSoup
import re
.
.
.

def main():
   b=mechanize.Browser()
   return b.open(mainlink+case)

html_text=main().read()

soup = BeautifulSoup(html_text)

g_data=soup.findAll("div",{"class":"Print"})

Case_info=open("case_info.txt", "w+")

for item in g_data:
  print item.text
  Case_info.write(item.text+"\n")

Case_info.close()

另外,让我有些困惑的是这部分代码几乎完美地完成了完全相同的事情。

.
.
links = soup.findAll('a',href=True)
.
.
for link in links:
  if re.findall('keyword',link['href']):
   #print link.text, link['href'] 
   files.write(link['href']+"\n")
   names.write(link.text+"\n")
.
.

希望有人可以帮助解决问题。

【问题讨论】:

    标签: python text web-scraping beautifulsoup mechanize


    【解决方案1】:

    使用unidecode 包,可以消除错误。

    from unidecode import unidecode
    for item in g_data:
      print item.text
      Case_info.write(unidecode (item.text+"\n"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-23
      • 2013-05-06
      • 2012-04-16
      • 2021-02-09
      • 2014-11-07
      • 2014-08-09
      • 1970-01-01
      • 2016-07-02
      相关资源
      最近更新 更多