Beautiful Soup 结果中的缺失部分 [英] Missing parts on Beautiful Soup results

查看:18
本文介绍了Beautiful Soup 结果中的缺失部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在以下 html 代码中检索几个 <p> 标签.这里只是一部分

<a class="fBlackLink"></a><中心></中心><跨度>... </span><br></br><table width="402" vspace="5" cellspacing="0" cellpadding="3"边框="0" bgcolor="#ffffff" align="左">... </tbody></table><!--edstart--><p>... </p><p>... </p><p>... </p><p>... </p><p>... </p></td>

您可以在此处找到网页

我的Python代码如下

soup = BeautifulSoup(page)div = 汤.find('td', attrs={'class': 'eelantext'})打印divtext = div.find_all('p')

但是文本变量是空的,如果我打印 div 变量,除了 <p> 标签之外,我有与上面完全相同的 html.

解决方案

BeautifulSoup 可以使用 处理 HTML 输入的不同解析器.这里的 HTML 输入有点损坏,默认的 HTMLParser 解析器不能很好地处理它.

改用html5lib解析器:

<预><代码>>>>len(BeautifulSoup(r.text, 'html').find('td', attrs={'class': 'eelantext'}).find_all('p'))0>>>len(BeautifulSoup(r.text, 'lxml').find('td', attrs={'class': 'eelantext'}).find_all('p'))0>>>len(BeautifulSoup(r.text, 'html5lib').find('td', attrs={'class': 'eelantext'}).find_all('p'))22

I am trying to retrieve few <p> tags in the following html code. Here is only the part of it

<td class="eelantext">
    <a class="fBlackLink"></a>
    <center></center>
    <span> … </span><br></br>
    <table width="402" vspace="5" cellspacing="0" cellpadding="3" 
        border="0" bgcolor="#ffffff" align="Left">
    <tbody> … </tbody></table>
      <!--edstart-->
    <p> … </p>
    <p> … </p>
    <p> … </p>
    <p> … </p>
    <p> … </p>
</td>

You can find the webpage here

My Python code is the following

soup = BeautifulSoup(page)
div = soup.find('td', attrs={'class': 'eelantext'})
print div
text = div.find_all('p') 

But the text variable is empty and if I print the div variable, I have exactly the same html from above except the <p> tags.

解决方案

BeautifulSoup can use different parsers to handle HTML input. The HTML input here is a little broken, and the default HTMLParser parser doesn't handle it very well.

Use the html5lib parser instead:

>>> len(BeautifulSoup(r.text, 'html').find('td', attrs={'class': 'eelantext'}).find_all('p'))
0
>>> len(BeautifulSoup(r.text, 'lxml').find('td', attrs={'class': 'eelantext'}).find_all('p'))
0
>>> len(BeautifulSoup(r.text, 'html5lib').find('td', attrs={'class': 'eelantext'}).find_all('p'))
22

这篇关于Beautiful Soup 结果中的缺失部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆