【问题标题】:Multiple conditions in BeautifulSoup: Text=True & IMG Alt=TrueBeautifulSoup 中的多个条件:Text=True & IMG Alt=True
【发布时间】:2020-08-15 08:40:30
【问题描述】:

有没有办法在 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。

感谢您的帮助。 谢谢!

【问题讨论】:

    标签: python selenium beautifulsoup


    【解决方案1】:

    .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
    

    【讨论】:

    • 它就像魅力兄弟一样,谢谢!我有一个问题,使用“yield from traverse(c)”或“yield from c”有什么区别。我认为两者都有相同的结果,但我很好奇为什么要使用相同的功能......我从来没有想过。
    • 有没有办法将结果存储在字符串变量中?
    • 知道了,刚刚在for循环中创建了一个str变量就完成了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    相关资源
    最近更新 更多