Kay
Kay

Reputation: 933

select multiple tags by position in beautifulSoup

Consider the following html:

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/tillie" class="sister" id="link3">Millie</a>
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""


 soup = bs4.BeautifulSoup(html_doc, 'html.parser')

If I want the 2nd a tag, I can do:

    soup.select("a:nth-of-type(2)")

But, if I want to select the 2nd, 3rd and 5th a tags, how can I do that? I tried with below which gave me errors

    soup.select("a:nth-of-type([2, 3, 5])")
    soup.select("a:nth-of-type(2, 3, 5)")

Upvotes: 0

Views: 380

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195573

Use CSS selector with comma ", ": 'a:nth-child(2), a:nth-child(3), a:nth-child(5)':

import requests
from bs4 import BeautifulSoup

html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>

<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/tillie" class="sister" id="link3">Millie</a>
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>

<p class="story">...</p>
"""

soup = BeautifulSoup(html_doc, 'html.parser')

a2, a3, a5 = soup.select('a:nth-child(2), a:nth-child(3), a:nth-child(5)')

print(a2)
print(a3)
print(a5)

Prints:

<a class="sister" href="http://example.com/tillie" id="link3">Millie</a>
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>
<a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>

More here: CSS Selectors Reference

Upvotes: 1

Stanislav Lipovenko
Stanislav Lipovenko

Reputation: 574

if your solution is not around CSS classes you better use soup.find_all()

needed_a_tags = [tag for i, tag in enumerate(soup.find_all('a')) if i in [1,2,4]]

Upvotes: 0

Related Questions