Is there any beautifulsoup function to select duplicate class names?

Viewed 190

There are two classes in my website, first, let's say wikitable something and second let's say wikitable.

I am trying to select the second class (wikitable) using the code soup.find('table',class_='wikitable') but all I am geting is the first class.

3 Answers

You already used the term in your question - use strict conditions like select("table[class='wikitable']"):

from bs4 import BeautifulSoup

html = """
<table class="wikitable something"></table>
<table class="wikitable"></table>
"""

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

tables = soup.select("table[class='wikitable']")
print(tables)

Output

[<table class="wikitable"></table>]

Addition If there is only one table that contains the single class name wikitable you can use also soup.select_one("table[class='wikitable']")

Use a :not() selector to exclude the other class.

wikitable = soup.select('table.wikitable:not(.something)')[0]

To select the second wikitable class, try using a CSS Selector: .class-name:nth-of-type(n).

For example:

print(soup.select_one('.wikitable:nth-of-type(2)'))
Related