BeautifulSoup:获取具有特定属性的元素,与其值无关

Raf*_*ini 2 python xpath parsing beautifulsoup html-parsing

想象一下,我有以下html:

<div id='0'>
    stuff here
</div>

<div id='1'>
    stuff here
</div>

<div id='2'>
    stuff here
</div>

<div id='3'>
    stuff here
</div>
Run Code Online (Sandbox Code Playgroud)

是否有一种简单的方法可以使用BeautifulSoup 提取div具有该属性的所有属性id,而与其值无关?我意识到用xpath做这件事是微不足道的,但似乎没有办法在BeautifulSoup中进行xpath搜索.

Mar*_*ers 5

用于id=True仅匹配具有属性集的元素:

soup.find_all('div', id=True)
Run Code Online (Sandbox Code Playgroud)

反作用也是如此; 您可以使用以下属性排除标记id:

soup.find_all('div', id=False):
Run Code Online (Sandbox Code Playgroud)

要查找具有给定属性的标记,您还可以使用CSS选择器:

soup.select('div[id]'):
Run Code Online (Sandbox Code Playgroud)

但不幸的是,这不支持搜索逆运算所需的运算符.

演示:

>>> from bs4 import BeautifulSoup
>>> sample = '''\
... <div id="id1">This has an id</div>
... <div>This has none</div>
... <div id="id2">This one has an id too</div>
... <div>But this one has no clue (or id)</div>
... '''
>>> soup = BeautifulSoup(sample)
>>> soup.find_all('div', id=True)
[<div id="id1">This has an id</div>, <div id="id2">This one has an id too</div>]
>>> soup.find_all('div', id=False)
[<div>This has none</div>, <div>But this one has no clue (or id)</div>]
>>> soup.select('div[id]')
[<div id="id1">This has an id</div>, <div id="id2">This one has an id too</div>]
Run Code Online (Sandbox Code Playgroud)