Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python BeautifulSoup.prettify()提供奇怪的输出_Python_Django_Beautifulsoup_Urllib2 - Fatal编程技术网

Python BeautifulSoup.prettify()提供奇怪的输出

Python BeautifulSoup.prettify()提供奇怪的输出,python,django,beautifulsoup,urllib2,Python,Django,Beautifulsoup,Urllib2,我正在尝试解析一个网站,稍后我将在Django项目中使用它。为此,我使用urllib2和BeautifulSoup4。然而,我无法得到我想要的。BeautifulSoup对象的输出很奇怪。我尝试了不同的页面,效果很好(输出正常)。我以为是因为这一页。然后,当我的朋友尝试做同样的事情时,他得到了正常的输出。我想不出这个问题 这是我要分析的问题 这是命令“soup.prettify()”之后奇怪输出的一个示例: td B G C O L O R=“#9 9 0 4 0 4”w i d t h=“3”

我正在尝试解析一个网站,稍后我将在Django项目中使用它。为此,我使用urllib2和BeautifulSoup4。然而,我无法得到我想要的。BeautifulSoup对象的输出很奇怪。我尝试了不同的页面,效果很好(输出正常)。我以为是因为这一页。然后,当我的朋友尝试做同样的事情时,他得到了正常的输出。我想不出这个问题

这是我要分析的问题

这是命令“soup.prettify()”之后奇怪输出的一个示例:

td 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 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便士。GIF“w i d t h=“6 0 0”\n 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&;nbsp&;nbsp&;nbsp&;n b s p;/p\n/b o d y\n/h t m l\n

\n\n'
下面是一个对我有用的最小示例,包括您有问题的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">
....
。。。。
....

您和您的朋友可能使用不同的解析器。BeautifulSoup将使用它认为“最好”的解析器,因此出于速度原因(如果已安装),它更喜欢
lxml
。如果使用Python的最新版本(以及所含解析器的最新版本),则可以通过
BeautifulSoup(text'html.parser')
更好地处理某些情况;这是一种情况,例如,当存在未屏蔽的
时,看起来您的XML带有beautifulsoup不期望的编码。我猜您的XML是UTF-16格式的,而beautifulsoup将其读取为UTF-8格式。Python提供了.encode和.decode函数,用于在不同编码之间切换。差不多

myXmlStr.encode("utf-16").decode("utf-8")
如果问题是传入的XML编码,则可能会解决您的问题。我自己对beautiful soup还不熟悉,但快速的google建议,如果问题是输出的编码,则prettify接受一个编码参数:

soup.prettify("utf-16")

如果没有更多的信息,我无法给你一个更清晰的答案,但希望这能为你指明一个有用的方向。

你能发布你使用的代码吗?它与@Hooked编写的代码类似。下面是我使用的:从bs4导入urllib2导入BeautifulSoup page=urllib2.open(“)soup=BeautifulSoup(page)print soup.prettify()它在我的计算机上给出了同样奇怪的输出。
soup.prettify("utf-16")