BeautifulSoup(html) 返回字母之间带有空格的文本



我正在使用美丽的汤来废弃此页面:url= http://www.ville-brunoy.fr/Brunoy.asp?idpage=3458.为此,我使用:

html=requests.get(url, headers=headers).text soup = BeautifulSoup(html).

但是,运行此命令时我得到的文本与预期不同(即与我检查 url 时得到的文本不同(。BeautifulSoup(( 在字母之间创建空白,输出如下所示:

s.className='';" onmouseover="MM_showHideLayers('letraitdunion','','show'); MM_swapImage('img_letraitdunion','','images2/fleche_survol.gif',1); this.className='li_social';">
<a href="brunoy.asp?idpage=4290">Le Trait d'Union</a></li>
</ul>
</dd>
</dl>
<a href="imprim_html.asp?idpage=3458&amp;lxml" target="_blank"><img a="" src="images2/impr.jpg">l t = " I m p r i m e r   l a   p a g e "   c l a s s = " i c o n e _ o u t i l "   / &gt; / a &gt; a   h r e f = " s i t e _ a c c e s . a s p ? i d P a g e = 3 4 5 8 &amp;i d = &amp;a p p e l = " &gt; i m g   s r c = " i m a g e s 2 / i m a g e s 2 o e i l . j p g "   a l t = " V e r s i o n   a c c e s s i b l e   a u x   m a l - v o y a n t s "   c l a s s = " o e i l "   / &gt; / a &gt; 

我已经在许多不同的网站上使用了此功能,但从未遇到过此问题。你知道它来自哪里吗?

谢谢

安东尼

问题来自您使用BeautifulSoup()的方式。
而不是这样做:

r = requests.get(url)
soup = BeautifulSoup(r.text)

您应该使用:

r = requests.get(url)
soup = BeautifulSoup(r.content,"lxml")

不同之处在于,使用text时,您以unicode(即 Unicode 字符串(传递响应的内容,而使用content则传递raw undecoded bytes.

最新更新