Python Forum
Extract something when you have multiple tags
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Extract something when you have multiple tags
#4
(Aug-03-2021, 11:51 AM)knight2000 Wrote: Would anyone be able to enlighten me on how to navigate through the current results to then go on to extract the 1 between the span tags please?
from bs4 import BeautifulSoup

html = '''\
<span class="nvb voteup"><i class="fa fa-plus"></i><span>1</span></span>'''
soup = BeautifulSoup(html, 'lxml')
Usage with CSS selector
>>> soup.select_one('body > span > span')
<span>1</span>
>>> soup.select_one('body > span > span').text
'1'
If more tag use select() then get a list of tag back that eg can loop over.
html = '''\
<span class="nvb voteup"><i class="fa fa-plus"></i><span>1</span></span>
<span class="nvb voteup"><i class="fa fa-plus"></i><span>2</span></span>
<span class="nvb voteup"><i class="fa fa-plus"></i><span>3</span></span>'''
Usage.
>>> tag = soup.select('body > span > span')
>>> tag
[<span>1</span>, <span>2</span>, <span>3</span>]
>>> for span in tag:
...     print(span.text)
...     
1
2
3

>>> [span.text for span in tag]
['1', '2', '3']
Reply


Messages In This Thread
RE: Extract something when you have multiple tags - by snippsat - Aug-04-2021, 01:21 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020