python - BeautifulSoup soup.prettify() 给出奇怪的输出

标签 python django beautifulsoup urllib2

我正在尝试解析一个网站,稍后我将在我的 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   "   &gt;   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   "   &gt;   /   t   d   &gt;   \n           /   t   r   &gt;   \n           t   r   &gt;   \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   "   &gt;   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   "   &gt;   /   t   d   &gt;   \n           /   t   r   &gt;   \n   /   t   a   b   l   e   &gt;   \n   /   c   e   n   t   e   r   &gt;   /   d   i   v   &gt;   \n   \n   p   &gt;   &amp;n   b   s   p   ;   &amp;n   b   s   p   ;   &amp;n   b   s   p   ;   &amp;n   b   s   p   ;   /   p   &gt;   \n   /   b   o   d   y   &gt;   \n   /   h   t   m   l   &gt;\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/

相关文章:

python - 如何将爬取的数据横向导出到Excel?

Python 网页抓取 - html 解析

python - 将卡住图从 .pb 转换为 .onnx

python - 合并两个字典列表

python - Python 中不使用范围的高效迭代

python - 表单初始数据不显示在模板中

python - django-cms 页面的绝对 url

python - formencode Schema 动态添加字段

python - Django 1.8,多种自定义用户类型

python - 将 html 实体文件转换为 Unicode(使用 BeautifulSoup 和 Python?)