如何通过css选择器匹配特定标签,其中class属性包含空格?

时间:2015-06-08 13:31:47

标签: python html css-selectors beautifulsoup html-parsing

我想选择一个{class}}标签,其值为class attribute:

table

所以我尝试了以下代码:

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

但它没有奏效:

  

ValueError:不支持或无效的CSS选择器:" table [class =" drug-table"

class属性值中的空格是导致无法匹配的原因。而且,我想要深入探讨另外两个元素:

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

1 个答案:

答案 0 :(得分:6)

要指定multiple classes in a CSS selector,请使用点连接它们:

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

演示:

>>> 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>