首页 > 解决方案 > 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。

我感谢您的帮助。谢谢!

标签: pythonseleniumbeautifulsoup

解决方案


.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

推荐阅读