2016-06-21 2 views
0

웹 페이지에서 목록을 가져 와서 컨텍스트를 제공하고 있습니다. 바로 앞의 텍스트도 가져옵니다. <ul> 또는 <ol> 태그 앞에 태그를 가져 오는 것이 가장 좋은 방법 인 것 같습니다. 그래서 나는이 목록이 있다고 가정 해 봅시다 :BeautifulSoup : 다른 태그 앞에 태그를 가져 오기

enter image description here

내가 총알과 단어 "밀레니엄"을 가져올 싶어. 내가 ul_with_context를 인쇄 할 때

#pull <ul> tags 
def pull_ul(tag): 
    return tag.name == 'ul' and tag.li and not tag.attrs and not tag.li.attrs and not tag.a 
ul_tags = webpage.find_all(pull_ul) 
#find text immediately preceding any <ul> tag and append to <ul> tag 
ul_with_context = [str(ul.previous_sibling) + str(ul) for ul in ul_tags] 

, 나는 다음과 같은 얻을 : 당신이 볼 수 있듯이

['\n<ul>\n<li>With immigration adding more numbers to its group than any other, the Millennial population is projected to peak in 2036 at 81.1 million. Thereafter the oldest Millennial will be at least 56 years of age and mortality is projected to outweigh net immigration. By 2050 there will be a projected 79.2 million Millennials.</li>\n</ul>'] 

는 "밀레니엄"이 뽑아되지 않은 내가 BeautifulSoup로 함수를 사용합니다. 나는에서 당기는거야 페이지는 http://www.pewresearch.org/fact-tank/2016/04/25/millennials-overtake-baby-boomers/ 여기 총알에 대한 코드의 섹션입니다입니다 :

enter image description here

<p><ul> 태그 형제 자매입니다. 왜 단어가 "Millennials"입니까?이라는 태그가 붙어있는 이유는 무엇입니까?

답변

-1

Previous_sibling은 태그 바로 앞에 문자열 또는을 반환합니다. 귀하의 경우에는 '\n' 문자열을 반환합니다.

대신 노드가 선택한 항목 앞 얻을 수있는 findPrevious method을 사용할 수

doc = """ 
<h2>test</h2> 
<ul> 
    <li>1</li> 
    <li>2</li> 
</ul> 
""" 

soup = BeautifulSoup(doc, 'html.parser')  
tags = soup.find_all('ul') 


print [ul.findPrevious() for ul in tags] 
print tags 

출력됩니다 : 내가 사용 BeautifulSoup로의 현재 버전에서

[<h2>test</h2>] 
[<ul><li>1</li><li>2</li></ul>] 
+0

, 방법 findPrevious()가 아닌 find_previous()입니다. –

관련 문제