使用beautifulsoup废弃<h2>标签</h2>

时间:2014-01-08 06:29:56

标签: python web-scraping beautifulsoup

我正在使用漂亮的汤来删除网站数据。我想要以下的锚值(我的名字是尼克)。但我在谷歌搜索了很多,但找不到任何完美的解决方案来解决我的问题。

news_panel = soup.findAll('div', {'class': 'menuNewsPanel_MenuNews1'})
for news in news_panel:
    temp = news.find('h2')        
    print temp

输出:

<h2 class="menuNewsHl2_MenuNews1"><a href="index.php?ref=MjBfMDFfMDhfMTRfMV84XzFfOTk2NDA=">My name is nick</a></h2>

但我想要这样的输出:My name is nick

3 个答案:

答案 0 :(得分:3)

抓住text属性:

>>> soup = BeautifulSoup('''<h2 class="menuNewsHl2_MenuNews1"><a href="index.php?ref=MjBfMDFfMDhfMTRfMV84XzFfOTk2NDA=">My name is nick</a></h2>''')
>>> soup.text
u'My name is nick'

答案 1 :(得分:2)

您的错误可能正在发生,因为您的输入字符串中没有该特定标记。

检查temp是否不是

news_panel = soup.findAll('div', {'class': 'menuNewsPanel_MenuNews1'})
for news in news_panel:
    temp = news.find('h2')
    if temp:
        print temp.text

或将您的print语句放在try ... except

news_panel = soup.findAll('div', {'class': 'menuNewsPanel_MenuNews1'})
for news in news_panel:
    try:
        print news.find('h2').text
    except AttributeError:
        continue

答案 2 :(得分:-1)

尝试使用:

all_string=soup.find_all("h2")[0].get_text()