0

我正在开发一些屏幕抓取软件,但遇到了 Beautiful Soup 的问题。我正在使用 python 2.4.3 和 Beautiful Soup 3.0.7a。

我需要删除一个<hr>标签,但它可以有许多不同的属性,所以一个简单的 replace() 调用不会删除它。

给定以下html:

<h1>foo</h1>
<h2><hr/>bar</h2>

以及以下代码:

soup = BeautifulSoup(string)

bad_tags = soup.findAll('hr');
[tag.extract() for tag in bad_tags] 

for i in soup.findAll(['h1', 'h2']):
    print i
    print i.string

输出是:

<h1>foo</h1>
foo
<h2>bar</h2>
None

我是否误解了提取功能,或者这是 Beautiful Soup 的错误?

4

2 回答 2

2

这可能是一个错误。但幸运的是,还有另一种获取字符串的方法:

from BeautifulSoup import BeautifulSoup

string = \
"""<h1>foo</h1>
<h2><hr/>bar</h2>"""

soup = BeautifulSoup(string)

bad_tags = soup.findAll('hr');
[tag.extract() for tag in bad_tags] 

for i in soup.findAll(['h1', 'h2']):
    print i, i.next

# <h1>foo</h1> foo
# <h2>bar</h2> bar
于 2009-05-12T23:58:12.850 回答
0

我有同样的问题。我不知道为什么,但我想这与 BS 创建的空元素有关。

例如,如果我有以下代码:

from bs4 import BeautifulSoup

html ='            \
<a>                \
    <b test="help">            \
        hello there!  \
        <d>        \
        now what?  \
        </d>    \
        <e>        \
            <f>        \
            </f>    \
        </e>    \
    </b>        \
    <c>            \
    </c>        \
</a>            \
'

soup = BeautifulSoup(html,'lxml')
#print(soup.find('b').attrs)

print(soup.find('b').contents)

t = soup.find('b').findAll()
#t.reverse()
for c in t:
    gb = c.extract()

print(soup.find('b').contents)

soup.find('b').text.strip()

我收到以下错误:

“NoneType”对象没有属性“next_element”

在我得到的第一张照片上:

>>> print(soup.find('b').contents)
[u' ', <d> </d>, u' ', <e> <f> </f> </e>, u' ']

第二次我得到:

>>> print(soup.find('b').contents)
[u' ', u' ', u' ']

我很确定是中间的空元素造成了问题。

我发现的一种解决方法是重新创建汤:

soup = BeautifulSoup(str(soup))
soup.find('b').text.strip()

现在它打印:

>>> soup.find('b').text.strip()
u'hello there!'

我希望这会有所帮助。

于 2016-04-22T13:23:06.087 回答