python - 使用python BeautifulSoup,如何找到所有带有NOT类的 'a'标签

标签 python html beautifulsoup

假设我有 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/

相关文章:

python - 如何在 Bottle 微框架中使用 beaker session?

python - PySide:如何获取包含给定小部件的布局?

python - 没有泡菜模块

javascript - div onclick 或 oncontext 在 cocoa 中的 webview 加载后仅工作一次

php - 使用 DOMXPath 在 <p> 标签内保留换行符?

javascript - 制作一个JS添加幻灯片

python - 如何使用 BeautilSoup 提取表信息?

python - 咖啡分类器

python - BeautifulSoup - 在维基百科页面上查找具有指定类的表

python - 为什么这个网站不能用 bs4 抓取?