假设我有 4 个链接:
<a href="#1" id="xyz" class="monte">hi</a>
<a href="#3" id="qrs" class="sam">hi</a>
<a href="#6" id="mno" class="alex">hi</a>
<a href="#9" id="abc" >hi</a>
我想返回所有没有 class = "monte"的元素的 href、class 和 id ...包括根本没有 class 元素的一个元素。我们假设上面的内容被称为 html
是否存在诸如!
之类的NOT运算符
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser") # or lxml
result = soup.find_all('a', {"class": !"monte"})
for link in result:
print(link.get("href"));
print(link.get("class"));
print(link.get("id"));
使用selenium
驱动程序,我想单击任何找到的元素。假设我可能没有唯一的 id
来识别要点击的内容。也就是说,我可能需要使用 find_element_by_xpath
。我确实有一个唯一的data-id
。
最佳答案
使用:not
排除特定类。使用 .has_attr
来测试尝试访问或使用 .get
时是否存在类以及默认值,例如print(i.get('class', 'None'))
。
from bs4 import BeautifulSoup as bs
from pprint import pprint
html = '''
<a href="#1" id="xyz" class="monte">hi</a>
<a href="#3" id="qrs" class="sam">hi</a>
<a href="#6" id="mno" class="alex">hi</a>
<a href="#9" id="abc" >hi</a>
'''
soup = bs(html, 'lxml')
for i in soup.select('a:not(.month)'):
print(i['href'])
print(i['id'])
if i.has_attr('class'):
print(i['class'])
如果您想导航到它们,那么您需要在 href 上使用 .get 方法:
links = [i['href'] in soup.select('a:not(.month)')]
for link in links:
driver.get(link)
关于python - 使用python BeautifulSoup,如何找到所有带有NOT类的 'a'标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66948880/