2010-03-23 2 views
7

BeautifulSoup과 함께 scrapy을 사용하여 땜질을 시작했습니다. 매우 명확한 것이 빠져 있는지 궁금하지만, 반환 된 doctype을 얻는 방법을 찾지 못했습니다. html 문서를 생성합니다. BeautifulSoup로를 사용에서 선언 된 문서 타입을 추출하는 방법이 경우문서 가져 오기 DOCTYPE with BeautifulSoup

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html lang="en"> 
<head> 
<meta charset=utf-8 /> 
<meta name="viewport" content="width=620" /> 
<title>HTML5 Demos and Examples</title> 
<link rel="stylesheet" href="/css/html5demos.css" type="text/css" /> 
<script src="js/h5utils.js"></script> 
</head> 
<body> 
<p id="firstpara" align="center">This is paragraph <b>one</b> 
<p id="secondpara" align="blah">This is paragraph <b>two</b>. 
</html> 

사람이 말해 줄 수 :

는 다음과 같은 HTML을 감안할 때?

답변

4

아름다운 수프 4 DOCTYPE 선언에 대한 클래스가 : 그럼 당신은이 선언의 종류를 알아 그것을 검사 할 수 있습니다 의심 할 여지없이 하나 또는 아무도 기대하지 않는다!)

def doctype(soup): 
    items = [item for item in soup.contents if isinstance(item, bs4.Doctype)] 
    return items[0] if items else None 
0

당신은 단지 수프 내용의 첫 번째 항목을 가져올 수 :

>>> soup.contents[0] 
u'DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"' 
+4

doctype이 첫 번째 항목이 아니라면이 구문은 깨질 것이다. 예를 들어, 문서 맨 위에 xml 선언이있는 경우. – karlcow

+2

doctype이 누락되어있을 수 있고 그럴 수 있기 때문에 아무 것도 반환 할 수 없습니다. – zvone

3

당신은 최상위 요소를 통해 이동하고 선언 있는지 여부를 확인하기 위해 각을 확인할 수 있습니다. 당신이있어 비록 당신이 (최상위 수준에있는 모든 선언을 추출하는 것을 사용할 수 있도록,

for child in soup.contents: 
    if isinstance(child, BS.Declaration): 
     declaration_type = child.string.split()[0] 
     if declaration_type.upper() == 'DOCTYPE': 
      declaration = child 
관련 문제