仅在具有两个类并且共享相同的第一个类时才选择元素

Mth*_*Clv 5 html python beautifulsoup css-selectors html-parsing

我在要解析的HTML中有这些元素:

<td class="line"> GARBAGE </td>
<td class="line text"> I WANT THAT </td>
<td class="line heading"> I WANT THAT </td>
<td class="line"> GARBAGE </td>
Run Code Online (Sandbox Code Playgroud)

如何创建一个CSS选择器,选择具有属性类行和类别的元素(可能是标题,文本或其他任何东西)但不仅仅属性类行?

我试过了:

 td[class=line.*]
 td.line.*
 td[class^=line.]
Run Code Online (Sandbox Code Playgroud)

编辑

我正在使用Python和BeautifulSoup:

url = 'http://www.somewebsite'
res = requests.get(url)
res.raise_for_status()
DicoSoup = bs4.BeautifulSoup(res.text, "lxml")
elems = DicoSoup.select('body div#someid tr td.line')
Run Code Online (Sandbox Code Playgroud)

我正在考虑修改最后一块,即td.line到类似的东西td.line.whateverotherclass(但不是单独的td.line,否则我的选择器就足够了)

ale*_*cxe 3

@BoltClock 建议的通常是解决 CSS 选择器问题的正确方法。唯一的问题是BeautifulSoup支持的CSS 选择器数量有限。例如,not()选择器目前是 :not(.supported)

您可以使用“starts-with”选择器来解决它,以检查类是否以line空格开头(它非常脆弱,但适用于您的示例数据):

for td in soup.select("td[class^='line ']"):
    print(td.get_text(strip=True))
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用find_all()搜索函数来检查class属性line和其他一些类来解决它:

from bs4 import BeautifulSoup

data = """
<table>
    <tr>
        <td class="line"> GARBAGE </td>
        <td class="line text"> I WANT THAT </td>
        <td class="line heading"> I WANT THAT </td>
        <td class="line"> GARBAGE </td>
    </tr>
</table>"""
soup = BeautifulSoup(data, 'html.parser')

for td in soup.find_all(lambda tag: tag and tag.name == "td" and
                                    "class" in tag.attrs and "line" in tag["class"] and
                                    len(tag["class"]) > 1):
    print(td.get_text(strip=True))
Run Code Online (Sandbox Code Playgroud)

印刷:

I WANT THAT
I WANT THAT
Run Code Online (Sandbox Code Playgroud)