Python BeautifulSoup:获取具有特定属性的元素,独立于其值
假设我有以下html:Python BeautifulSoup:获取具有特定属性的元素,独立于其值,python,parsing,xpath,html-parsing,beautifulsoup,Python,Parsing,Xpath,Html Parsing,Beautifulsoup,假设我有以下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> 这里的东西 这里的东西 这里的东西 这里的东西 是否有一种简单的方法可以提取所有具有属性
<div id='0'>
stuff here
</div>
<div id='1'>
stuff here
</div>
<div id='2'>
stuff here
</div>
<div id='3'>
stuff here
</div>
这里的东西
这里的东西
这里的东西
这里的东西
是否有一种简单的方法可以提取所有具有属性
id
的div
,而不依赖于使用BeautifulSoup的值?我意识到使用xpath执行此操作很简单,但似乎无法在BeautifulSoup中执行xpath搜索。使用id=True
仅匹配具有属性集的元素:
soup.find_all('div', id=True)
反之亦然;您可以排除具有id
属性的标记:
soup.find_all('div', id=False):
要查找具有给定属性的标记,还可以使用:
但不幸的是,这不支持搜索逆运算所需的运算符
演示:
>>来自bs4导入组
>>>样本='''\
... 这有一个身份证
... 这个没有
... 这个也有身份证
... 但这个人没有线索(或身份证)
... '''
>>>汤=美汤(样本)
>>>soup.find_all('div',id=True)
[这个有身份证,这个也有身份证]
>>>soup.find_all('div',id=False)
[这个没有,但这个没有线索(或id)]
>>>soup.select('div[id]”)
[这个有身份证,这个也有身份证]
BeautifulSoup4支持
导入bs4
>>>
>>>汤=bs4.BeautifulSoup(“”)
这
……不是这个
…这也是
... ''')
>>>soup.select('div[id]”)
[这个,这个也是]
官方文件在我看来相当不错:
soup.select('div[id]'):
>>> 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>]
>>> import bs4
>>>
>>> soup = bs4.BeautifulSoup('''
... <div id="0"> this </div>
... <div> not this </div>
... <div id="2"> this too </div>
... ''')
>>> soup.select('div[id]')
[<div id="0"> this </div>, <div id="2"> this too </div>]