2016-08-06 3 views

답변

0

사용 text 인수를 알고 Comment 할 유형을 선택하면 내가 텍스트 1을 얻을 필요가 실제로

<html> 
<body> 
<div> 
<!-- some commented code here!!!<div><ul><li><div id='ANY_ID'>TEXT_1</div></li> 
<li><div>other text</div></li></ul></div>--> 
</div> 
</body> 
</html> 

내부의 지정된 문자열에 코멘트를 찾을 수있는 방법. 그런 다음 다시 BeautifulSoup와 내용을로드하고 id하여 원하는 요소를 찾을 수 :

from bs4 import BeautifulSoup 
from bs4 import Comment 

data = """ 
<html> 
<body> 
<div> 
<!-- some commented code here!!!<div><ul><li><div id='ANY_ID'>TEXT_1</div></li> 
<li><div>other text</div></li></ul></div>--> 
</div> 
</body> 
</html> 
""" 

soup = BeautifulSoup(data, "html.parser") 
comment = soup.find(text=lambda text: isinstance(text, Comment) and "ANY_ID" in text) 

soup_comment = BeautifulSoup(comment, "html.parser") 
text = soup_comment.find("div", id="ANY_ID").get_text() 
print(text) 

인쇄 TEXT_1합니다.