我正在用beauthulsoup来抓取网络文章。输出正确打印,但未将完整输出写入文件。一旦碰到一个被引用的句子,它似乎就断了。以下是相关代码。任何见解都会非常有帮助。在
使用此URL复制结果:http://www.reuters.com/article/2014/03/06/us-syria-crisis-assad-insight-idUSBREA250SD20140306
import urllib2
from bs4 import BeautifulSoup
import re
import codecs
# Ask user to enter URL
url = raw_input("Please enter a valid URL: ")
# Make sure file is clear for new content
open('ctp_output.txt', 'w').close()
# Open txt document for output
txt = open('ctp_output.txt', 'w')
# Parse HTML of article, aka making soup
soup = BeautifulSoup(urllib2.urlopen(url).read())
# retrieve all of the paragraph tags
with open('ctp_output.txt', 'w'):
for tag in soup.find_all('p'):
txt.write(tag.text.encode('utf-8') + '\n' + '\n')
# Close txt file with new content added
txt.close()
如果你在休·博思韦尔的修改之后得到了
UnicodeEncodeError: 'ascii' codec can't encode characters in position 21-23: ordinal not in range(128)
,那么还需要执行以下操作使用
codecs.open()
或io.open()
使用适当的文本编码(即encoding=“…”)打开文本文件,而不是使用open()打开bytefile。在就写吧
^{pr2}$您需要
import codecs
来完成此操作几个问题:
需要进一步缩进(它应该是
^{pr2}$with open('ctp_output.txt', 'w') as f:
的子级是多余的-
with
语句已经确保文件被关闭我看不出输出中有什么遗漏-你能举出一个消失的句子吗?在
编辑:这看起来像是Python3的问题-它在python2.7.5中完美地工作
编辑2:已修复str.解码():
你的代码可以简化为
我猜你应该用utf8编码你要写的东西:
那是我最近的广告。在
相关问题 更多 >
编程相关推荐