作为属性值传递True
将匹配具有该属性的所有元素:
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''<select>
... <option value="0">2002/12</option>
... <option value="1">2003/12</option>
... <option value="2">2004/12</option>
... <option value="3">2005/12</option>
... <option value="4">2006/12</option>
... <option value="5" selected>2007/12</option>
... </select>''')
>>> soup.find_all('option', selected=True)
[<option selected="" value="5">2007/12</option>]
>>> soup.find_all('option', {'selected': True})
[<option selected="" value="5">2007/12</option>]
并使用 lxml:
>>> from lxml import etree
>>> root = etree.HTML('''<select>
<option value="0">2002/12</option>
<option value="1">2003/12</option>
<option value="2">2004/12</option>
<option value="3">2005/12</option>
<option value="4">2006/12</option>
<option value="5" selected>2007/12</option>
</select>''')
>>> root.xpath('//option[@selected]')
[<Element option at 0x228b7d0>]