2013-05-01 3 views
1

Python과 Beautifulsoup을 사용하여 HTML 데이터를 구문 분석하고 RSS 피드에서 p 태그를 가져옵니다. 그러나 파싱 된 수프 객체가 문서의 모든 노드를 포함하지 않기 때문에 일부 URL은 문제를 일으 킵니다.Beautifulsoup lost nodes

예를 들어 내가

그러나 페이지의 소스 코드를 구문 분석 된 개체를 비교 한 후 http://feeds.chicagotribune.com/~r/ChicagoBreakingNews/~3/T2Zg3dk4L88/story01.htm 구문 분석을 시도, 나는 ul class="nextgen-left" 후 모든 노드가없는 것으로 나타났습니다.

from bs4 import BeautifulSoup as bs 

url = 'http://feeds.chicagotribune.com/~r/ChicagoBreakingNews/~3/T2Zg3dk4L88/story01.htm' 

cj = cookielib.CookieJar() 
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) 
request = urllib2.Request(url) 

response = opener.open(request) 

soup = bs(response,'lxml')   
print soup 
+2

다른 파서를 사용해보십시오. 피드의 HTML이 손상되고 다른 파서가이를 다르게 처리합니다. –

답변

6

입력 HTML은 매우 준수하지, 당신은 여기에 다른 파서를 사용해야합니다 그래서 : 여기

내가 문서를 구문 분석하는 방법이다. html5lib 파서가이 페이지를 올바르게 처리합니다.

>>> import requests 
>>> from bs4 import BeautifulSoup 
>>> r = requests.get('http://feeds.chicagotribune.com/~r/ChicagoBreakingNews/~3/T2Zg3dk4L88/story01.htm') 
>>> soup = BeautifulSoup(r.text, 'lxml') 
>>> soup.find('div', id='story-body') is not None 
False 
>>> soup = BeautifulSoup(r.text, 'html5') 
>>> soup.find('div', id='story-body') is not None 
True