abdoulsn
abdoulsn

Reputation: 1159

Get data within an <a> within span tag

I stuck in getting all data within span tag. My code gives me only every first value in every a() within the span tag and ignore other values. In my example: (NB I reduced the span contents here, but it lot of inside)

<span class="block-niveaux-sponsors">
<a href="http://www.keolis.com/" id="a47-logo-part-keolis" target="_blank">
<img src="images/visuels_footer/footer/part_keolis.201910210940.jpg"/>
</a>
<div class="clearfix"></div>
</span>

<span class="block-niveaux-sponsors">
<a href="http://www.cg47.fr/" id="a47-logo-part-cg47" target="_blank">
<img src="images/visuels_footer/footer/part_cg47.201910210940.jpg"/>
</a>
<div class="clearfix"></div>
</span>

<span class="block-niveaux-sponsors">
<a href="http://www.errea.it/fr/" id="a47-logo-part-errea" target="_blank">
<img src="images/visuels_footer/footer/part_errea.201910210940.jpg"/>
</a>
<div class="clearfix"></div>
</span>

My code is:

page = urlopen(lien_suagen)
soup = bs(page, 'html.parser')
title_box_agen = soup.find_all('div', attrs={'id':'autres'})
for tag in title_box_agen:
    for each_row in tag.find_all('span'):
        links = each_row.find('a', href=True)
        title = links.get('id')
        print(title)

This give me only the first id values in . I want all id.

Upvotes: 1

Views: 55

Answers (2)

Jona
Jona

Reputation: 1286

You should try:

page = urlopen(lien_suagen)
soup = bs(page, 'html.parser')
title_box_agen = soup.find_all('div', attrs={'id':'autres'})
for tag in title_box_agen:
    for each_row in tag.find_all('span'):
        links = each_row.find_all('a', href=True)
        for link in links:
            title = link.get('id')
            print(title)

Upvotes: 1

Ollie in PGH
Ollie in PGH

Reputation: 2629

You can get all the link ids for each of the niveux class like this. (not tested)

page = urlopen(lien_suagen)
soup = bs(page, 'html.parser')
spans_niveux = soup.find_all('span' class_='block-niveaux-sponsors')
for span in spans_niveux:
    link = span.find('a', href=True)
    id = link.id
    print(id)

Upvotes: 1

Related Questions