【问题标题】:How to match a particular tag through css selectors where the class attribute contains spaces?如何通过类属性包含空格的css选择器匹配特定标签?
【发布时间】:2015-08-22 23:59:18
【问题描述】:

我想选择一个table标签,它的类属性值为:

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

所以我尝试了以下代码:

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

但它无法工作:

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

类属性值中的空格是无法匹配的原因。而且,我还想了解另外两个元素的深度,例如:

soup.select('table[class="drug-table data-table table table-condensed table-bordered"] > tr > th')

【问题讨论】:

  • 你累了吗find_all
  • 我讨厌 findall.. ya findall 有效.. 但我想要 css 选择器..

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


【解决方案1】:

要指定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>

【讨论】:

    猜你喜欢
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 2016-03-03
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多