【问题标题】:How to extract text between <h1></h1> in Python?如何在 Python 中提取 <h1></h1> 之间的文本?
【发布时间】:2014-10-19 06:46:03
【问题描述】:

我无法在 &lt;h1&gt;&lt;/h1&gt; 之间提取文本。

请帮帮我。

我的代码是:

import bs4
import re
import urllib2

url2='http://www.flipkart.com/mobiles/pr?sid=tyy,4io&otracker=ch_vn_mobile_filter_Top%20Brands_All#jumpTo=0|20'
htmlf = urllib2.urlopen(url2)
soup = bs4.BeautifulSoup(htmlf)
#res=soup.findAll('div',attrs={'class':'product-unit'})
for res in soup.findAll('a',attrs={'class':'fk-display-block'}):
    suburl='http://www.flipkart.com/'+res.get('href')
    subhtml = urllib2.urlopen(suburl)
    subhtml = subhtml.read()
    subhtml = re.sub(r'\s\s+','',subhtml)
    subsoup=bs4.BeautifulSoup(subhtml)
    res2=subsoup.find('h1',attrs={'itemprop':'name'})
    if res2:
        print res2

输出:

<h1 itemprop="name">Moto G</h1>
<h1 itemprop="name">Moto E</h1>
<h1 itemprop="name">Moto E</h1>

但我想要这个:

Moto G
Moto E
Moto E

【问题讨论】:

    标签: python html tags beautifulsoup extract


    【解决方案1】:

    你可以试试这个:

     res2=subsoup.find('h1',attrs={'itemprop':'name'})
        if res2:
            print res2.text
    

    添加 res2.text 即可解决问题。

    【讨论】:

      【解决方案2】:

      在任何 HTML 标记上,执行 get_text() 会给出与标记关联的文本。所以,你只需要在 res2 上使用get_text()。即,

      if res2:
          print res2.get_text()
      

      PS:作为旁注,我认为代码中的这一行 subhtml = re.sub(r'\s\s+','',subhtml) 是一项昂贵的操作。如果您所做的只是摆脱过多的空间,您可以这样做:

      if res2:
          print res2.get_text().strip()
      

      【讨论】:

      • 您也可以使用res2.text 代替res2.get_text()。更多信息here.
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      • 2020-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多