2014-03-24 1 views
2


저는 파이썬에 익숙합니다.BS4 + Python3 : 'NavigableString'개체에 'has_attr'속성이 없습니다.

Heres는 내 코드

내가하고 싶은 것은 속성 "확인해"만 세부 사항 (HREF 및 .string)를 얻을 수있다

<h1 class="entry-title"> 
<a href="test1.html">test1</a></h1> 
<h1 class="entry-title"> 
<a href="test2.html" rel="bookmark">test2</a></h1> 

:

여기에 내가 함께 연습하고 간단한 운동이다

for h1_Tag in soup.find_all(("h1", { "class" : "entry-title" })): 
    for a_Tag in h1_Tag.contents: 
     if a_Tag.has_attr('rel'): 
      print (a_Tag) 

AttributeError : 'NavigableString'객체에 'has_attr'속성이 없습니다.

내가 뭘 잘못하고 있니? 도움을 주시면 감사하겠습니다.

감사합니다.

답변

1

NavigableString 개체를 비롯한 모든 콘텐츠를 반복합니다. 예 : 본문. 당신이하는 rel 속성을 가진 모든 요소를 ​​찾을 대신 그들을 위해 검색하고 싶다면

:

for h1_Tag in soup.find_all(("h1", { "class" : "entry-title" })): 
    for a_Tag in h1_Tag.find_all('a', rel=True): 
     print(a_Tag) 

rel=True 키워드 인수는 그 속성이 요소에 대한 검색을 제한합니다; rel 속성이없는 <a> 태그는 건너 뜁니다.

+0

고맙습니다! 이 작품 –

1

대안은 SoupStrainer을 사용하는 것입니다. 이렇게하면 미리 정의 된 조건에 따라 문서를 구문 분석 할 수 있습니다. Python 2.7과 BeautifulSoup 4.3.2를 사용하면 논리가 유사합니다.

from bs4 import BeautifulSoup as bsoup, SoupStrainer as strain 

ofile = open("test.html") 
strain = strain(rel=True) 
soup = bsoup(ofile, parse_only=strain) 

print soup 

결과 :

<a href="test2.html" rel="bookmark">test2</a> 
[Finished in 0.2s] 

이 도움이되는지 알려 주시기 바랍니다.