我正在研究一些屏幕抓取软件,并遇到了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的错误?
答案 0 :(得分: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
答案 1 :(得分: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!'
我希望有所帮助。