python - BeautifulSoup 中的多个条件:Text=True & IMG Alt=True
问题描述
有没有办法在 BeautifulSoup 中使用多个条件?
这是我喜欢一起使用的两个条件:
获取文本:
soup.find_all(text=True)
获取 img alt:
soup.find_all('img', title=True):
我知道我可以单独做,但我想把它放在一起以保持 HTML 的流动。
我这样做的原因是因为只有 BeautifulSoup 通过 css 提取隐藏文本:显示无。
当您使用 driver.find_element_by_tag_name('body').text 时,您会得到 img alt att,但不幸的是,不是 css 的隐藏文本:display:none。
我感谢您的帮助。谢谢!
解决方案
.find_all()
仅返回文本或标签,但您可以创建自己的函数,从汤中返回文本并从alt=
属性中返回文本。
例如:
from bs4 import BeautifulSoup, Tag, NavigableString
txt = '''
Some text
<img alt="Some alt" src="#" />
Some other text
'''
def traverse(s):
for c in s.contents:
if isinstance(c, Tag):
if c.name == 'img' and 'alt' in c.attrs:
yield c['alt']
yield from traverse(c)
elif isinstance(c, NavigableString):
yield c
soup = BeautifulSoup(txt, 'html.parser')
for text in traverse(soup):
print(text.strip())
印刷:
Some text
Some alt
Some other text
推荐阅读
- python - 在经过固定次数的迭代后进行训练时,有什么方法可以备份 YOLOv5 中的权重?
- database - 如何将初始数据插入 Mendix 数据库?
- python - 如何在 GraphQL 中表达输入验证
- c# - 垃圾收集器在 WeakReference 中删除(收集)对象的优先级是多少?
- css - 网格列的 margin-top
- c++ - QT - 如何在滚动区域上添加按钮(具有绝对位置)
- java - 为什么在单个参数 lambda 上添加括号会产生代码异味?
- javascript - Vue.js - 引导表更新消耗太多内存
- java - 使用泛型在java上查找重复项
- vue.js - 从 npm 打包的 vue 组件库传递/访问应用程序的服务