2016-06-21 18 views
0

私はウェブページ上のリストを引っ張り、それらのコンテキストを与えるために、それらの直前のテキストも引き出します。 <ul>または<ol>タグの前のタグをプルするのが最善の方法です。それでは、私はこのリストを持っているとしましょう:BeautifulSoup:別のタグに先行するタグを引き出す

enter image description here

私は弾丸と単語「新世紀世代を」プルにしたいと思います。私はBeautifulSoup機能を使用します。

#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] 

私はul_with_contextを印刷し、私は次を得る:

['\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>'] 

あなたが見ることができるように、 "新世紀世代は" 引っ張られていませんでした。私はから引っ張ってるページはこちら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()です。 –

関連する問題