4

I want to select a table tag which has the value of class attribute as:

drug-table data-table table table-condensed table-bordered

So I tried the below code:

for i in soup.select('table[class="drug-table data-table table table-condensed table-bordered"]'):
    print(i)

But it fails to work:

ValueError: Unsupported or invalid CSS selector: "table[class="drug-table"

spaces in the class attribute value is the cause for not getting a match. And also, I want to go through two more elements depth like:

soup.select('table[class="drug-table data-table table table-condensed table-bordered"] > tr > th')
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274

1 Answers1

6

To specify multiple classes in a CSS selector, join them with dots:

soup.select("table.drug-table.data-table.table.table-condensed.table-bordered")

Demo:

>>> from bs4 import BeautifulSoup
>>> 
>>> data = """
... <table class="drug-table data-table table table-condensed table-bordered">
...     <tr>
...         <td>test</td>
...     </tr>
... </table>
... """
>>> 
>>> soup = BeautifulSoup(data)
>>> for i in soup.select("table.drug-table.data-table.table.table-condensed.table-bordered > tr > td"):
...     print(i)
... 
<td>test</td>
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195