使用beautifulsoup python从标签中提取html数据

时间:2017-02-22 19:48:10

标签: python html beautifulsoup html-parsing

我已将目标字符串缩小为以下html:

<h2 class="user-name"> John Kennity <span class="top-class"><a href="http://service-web.com/2008-07-31/11" target="_blank">highest rank </a></span>
</h2>

我想访问John Kennith这个名字。我怎么能在beautifulsoup python中做到这一点?

2 个答案:

答案 0 :(得分:1)

import bs4

text = '''<h2 class="user-name"> John Kennity <span class="top-class"><a href="http://service-web.com/2008-07-31/11" target="_blank">highest rank </a></span>
</h2>'''

soup = bs4.BeautifulSoup(text, 'lxml')
name, rank = soup.h2.stripped_strings

出:

'John Kennity'

答案 1 :(得分:0)

希望这有帮助。

user_names = soup.findAll('div', {'class': 'user-name'})
for un in user_names:
   temp = un.find('h2')
   if temp:
      print temp.text