2012-01-13 11 views
-1

HTML内のタグのインデックスを見つけるのpython文字列

<div class="productDescriptionWrapper"> 
<p>A worm worth getting your hands dirty over. With over six feet of crawl space, Playhut&rsquo;s Wiggly Worm is a brightly colored and friendly play structure. 
</p> 
<ul> 
    <li>6ft of crawl through fun</li>  
    <li>18&rdquo; diameter for easy crawl through</li>  
    <li>Bright colorful design</li>  
    <li>Product Measures: 18&quot;&quot;Diam x 60&quot;&quot;L</li>  
    <li>Recommended Ages: 3 years &amp; up<br /> &nbsp;</li> 
</ul> 
<p><strong>Intended for Indoor Use</strong></p> 

コード

def GetBullets(self, Soup): 

    bulletList = [] 

    bullets = str(Soup.findAll('div', {'class': 'productDescriptionWrapper'})) 

    bullets_re = re.compile('<li>(.*)</li>') 

    bullets_pat = str(re.findall(bullets_re, bullets)) 

    index = bullets_pat.findall('</li>') 

    print index 

方法pタグとliタグを抽出する

?ありがとう!

+0

<コメントが削除されました> –

+0

注意してください。これらのタグは相互に入れ子にすることができます。つまり、REは開始タグと終了タグを適切に一致させません。だから、(おそらく)BeautifulSoupのようなパーサを使うべきです。 –

+2

あなたはBeautifulSoupを使ってdivを見つけてそれを放棄し、文字列を正規表現で解析しようとしました。私は、あなたがBeautifulSoupに全面的にこだわることをお勧めします。 – sgallen

答えて

3

お知らせ:

>>> from BeautifulSoup import BeautifulSoup 
>>> html = """ <what you have above> """ 
>>> Soup = BeautifulSoup(html) 
>>> bullets = Soup.findAll('div', {'class': 'productDescriptionWrapper'}) 
>>> ptags = bullets[0].findAll('p') 
>>> print ptags 
[<p>A worm worth getting your hands dirty over. With over six feet of crawl space,  Playhut&rsquo;s Wiggly Worm is a brightly colored and friendly play structure. 
</p>, <p><strong>Intended for Indoor Use</strong></p>] 
>>> print ptags[0].text 
A worm worth getting your hands dirty over. With over six feet of crawl space, Playhut&rsquo;s Wiggly Worm is a brightly colored and friendly play structure. 

あなたは同様にあなたのliタグの内容を取得することができます。