2017-09-22 2 views
0

는 파이썬 lxml이 클라이언트를 사용하고 내가 분석하고 내가 원하는 요소를 얻을 수있는 다음 코드를 시도했지만 그냥 빈 반환특정 ID 이름을 가진 div를 찾고 lxml을 사용하여 자식을 반복하는 방법은 무엇입니까?

from lxml import html 
tree = html.fromstring(html_content) 
posts = tree.xpath('//*[@id="posts"]/div') 
for post in posts: 
    print post 

다음과 같이 HTML 코드는 같습니다

<div> 
    <div> 
    ... 
    <div id="posts"> 
     <div> 
      <div class="post"> 
       <a href="">User 1</a> 
       <div class="content"> Content 1</div> 
      </div> 
      <div class="post"> 
       <a href="">User 2</a> 
       <div class="content"> Content 2</div> 
      </div> 
      ... 
     </div> 
    </div> 
    ... 

post을 반복하여 <a> 태그와 <div> 내용에 액세스하고 싶습니다. 나는 인쇄 싶습니다

User 1 
Content 1 

User 2 
Content 2 

... 

답변

1

유사한 구문을 사용하여 클래스 post에 태그를 대상으로 쉬울 수 :

posts = tree.xpath('//*[@id="posts"]/div/*[@class="post"]') 
for post in posts: 
    print post.find('a').text 
    print post.find('div').text # add .strip() to clean the leading space 

출력 :

User 1 
Content 1 

User 2 
Content 2 
+0

위의 문제가 있다는 것입니다 'post' 클래스는 페이지 내에서 많이 사용됩니다. 나는'posts' id의 자식 인'post'에만 관심이 있습니다. – Cory

+0

편집이 더 좋습니다? – PRMoureu

관련 문제