![](/img/trans.png)
[英]I want to create an txt file on my desptop, then i want to download the html string of a website and safe it in the txt file
[英]I want to save my parsed HTML file into TXT file
我已經解析了一個顯示文章的網頁。 我想將解析的數據保存到文本文件中,但是我的python shell顯示如下錯誤:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 107: ordinal not in range(128)
這是我的代碼的一部分
search_result = urllib.urlopen(url)
f = search_result.read()
#xml parsing
parsedResult = xml.dom.minidom.parseString(f)
linklist = parsedResult.getElementsByTagName('link') #extracting links
extractedURL = linklist[3].firstChild.nodeValue #pick one link
page = urllib.urlopen(extractedURL).read()
#making html file
g= open('yyyy.html', 'w')
g.write(page)
g.close()
#reading html file and parsing html to get pure text of article
g= open('yyyy.html', 'r')
bs = BeautifulSoup(g,fromEncoding="utf-8")
g.close()
article = bs.find(id="articleBody")
content = article.get_text()
#save as a text file
h= open('yyyy.txt', 'w')
h.write(content)
h.close()
我應該添加些什么來使它起作用?
試試看
import codecs
h = codecs.open('yyyy.txt', 'w', 'utf-8')
或使用Python 3。
嘗試使用unidecode:
from unidecode import unidecode
unidecode(page)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.