编辑:我不敢相信BeautifullSoup实际上无法正确解析HTML。实际上我可能做错了什么,但如果我不这样做,这是一个真正的业余模块。在
我试图从网上获取文本,但我不能这样做,因为我总是得到一些奇怪的字符在大多数句子。我从来没有得到一个句子包含“不正确”这样的词。在
useragent = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11'}
request = urllib2.Request('SomeURL',None,useragent)
myreq = urllib2.urlopen(request, timeout = 5)
html = myreq.read()
#get paragraphs
soup = BeautifulSoup(html)
textList = soup.find_all('p')
mytext = ""
for par in textList:
if len(str(par))<2000:
print par
mytext +=" " + str(par)
print "the text is ", mytext
结果包含一些奇怪的字符:
^{pr2}$很明显,我想要的是不是而不是™t、 我该怎么办?在
我相信问题出在你的系统输出编码,它不能正确地输出编码字符,因为它超出了显示的字符范围。在
beauthoulsoup4旨在完全支持HTML实体。在
注意这些命令的奇怪行为:
我建议将输出写入文本文件,或者使用其他终端/更改终端设置以支持更广泛的字符范围。在
由于这是Python2,
urllib.urlopen().read()
调用返回一个字节字符串,很可能是用UTF-8编码的——您可以查看HTTP报头来查看是否包含了编码。我假设是UTF-8。在在你开始处理内容之前,你不能解码这个外部的表现,这只会导致你流泪。一般规则:立即解码输入,仅对输出进行编码。在
以下是您的代码,只有两个修改
我所做的只是添加了}。在
html
的unicode解码,并使用了soup.findAll()
,而不是{这是一个基于人们的答案和我的研究的解决方案。在
相关问题 更多 >
编程相关推荐