我正在尝试解析一个网站,稍后我将在我的 Django 项目中使用它。为此,我使用了 urllib2 和 BeautifulSoup4。然而,我得不到我想要的。 BeautifulSoup 对象的输出很奇怪。我尝试了不同的页面,它起作用了(输出是正常的)。我认为这是因为页面。然后,当我的 friend 尝试做同样的事情时,他得到了正常的输出。我无法找出问题所在。
这是 website我要解析了。
这是命令“soup.prettify()”后奇怪输出的示例:
t d B G C O L O R = " # 9 9 0 4 0 4 " w i d t h = " 3 " > i m g S R C = " 1 p . g i f " A L T B O R D E R = " 0 " h e i g h t = " 1 " w i d t h = " 3 " > / t d > \n / t r > \n t r > \n t d c o l s p a n = " 3 " B G C O L O R = " # 9 9 0 4 0 4 " w i d t h = " 6 0 0 " h e i g h t = " 3 " > i m g s r c = " 1 p . g i f " w i d t h = " 6 0 0 " \n h e i g h t = " 1 " > / t d > \n / t r > \n / t a b l e > \n / c e n t e r > / d i v > \n \n p > &n b s p ; &n b s p ; &n b s p ; &n b s p ; / p > \n / b o d y > \n / h t m l >\n </p>\n </body>\n</html>'
最佳答案
这是一个确实对我有用的最小示例,包括您遇到问题的 html 片段。没有你的代码很难说,但我猜你在某处做了类似 ' '.join(A.split())
的事情。
import urllib2, bs4
url = "http://kafemud.bilkent.edu.tr/monu_tr.html"
req = urllib2.urlopen(url)
raw = req.read()
soup = bs4.BeautifulSoup(raw)
print soup.prettify().encode('utf-8')
给予:
....
<td bgcolor="#990404" width="3">
<img alt="" border="0" src="1p.gif" width="3"/>
</td>
<td bgcolor="#FFFFFF" valign="TOP">
<div align="left">
<table align="left" border="0" cellpadding="10" cellspacing="0" valign="TOP" width="594">
<tr>
<td align="left" valign="top">
<table align="left" border="0" cellpadding="0" cellspacing="0" class="icerik" width="574">
....
关于python - BeautifulSoup soup.prettify() 给出奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20906416/