2009-05-12 3 views
0

일부 화면 스크래핑 소프트웨어로 작업 중이며 Beautiful Soup에 문제가 있습니다. 파이썬 2.4.3과 아름다운 스프 3.0.7a를 사용하고 있습니다.Beautiful Soup 추출시 오류가 발생했습니다.

<hr> 태그를 제거해야하지만 많은 다른 속성을 가질 수 있으므로 replace()를 호출해도 태그가 잘리지 않습니다.

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

그리고 다음 코드 : 다음 HTML을 감안할 때

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 

내가 추출 기능을 오해하고 있는가, 또는 이것을이다 아름다운 수프와 버그?

답변

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 
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' object has no attribute '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!' 

나는 희망이 도움이

내가 찾은 해결 방법은 바로 수프를 재현하는 것입니다.

관련 문제