推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
pppguest3962
V2EX  ›  Python

Beautifulsoup.find, attrs 多条件的问题

  •  
  •   pppguest3962 · Jun 6, 2023 · 1494 views
    This topic created in 1211 days ago, the information mentioned may be changed or developed.

    hSection 是<class 'bs4.element.ResultSet'>
    在使用 find 时:
    hSection.find_all('div',attrs={'class':'bts'))
    但结果还是很多不要的,实际上条件还要多一些,
    如:
    在以上条件前提下,还要属性'style'不能是'display:none;'

    虽然紧接着多写几句 if ,for .children ,也能最终找到目标节点,
    但想问,能否在 find() & find_all()方法里,一句就写完“是和非”的多条件完全匹配呢?

    deplivesb
        1
    deplivesb  
       Jun 6, 2023   ❤️ 1
    results = soup.findAll(lambda tag: tag.attrs.get("class") == ["bts"] and tag.attrs.get("style") == "display:none")
    deplivesb
        2
    deplivesb  
       Jun 6, 2023   ❤️ 1
    @deplivesb 忘了你要 div
    soup.findAll(lambda tag: tag.name == "div" and tag.attrs.get("class") == ["bts"] and tag.attrs.get("style") == "display:none")
    deplivesb
        3
    deplivesb  
       Jun 6, 2023   ❤️ 1
    @deplivesb #2

    soup.findAll(lambda tag:
    tag.name == "div" and
    tag.attrs.get("class") == ["bts"] and
    "display:none" not in tag.attrs.get("style", [])
    )
    pppguest3962
        4
    pppguest3962  
    OP
       Jun 6, 2023
    @deplivesb

    谢谢,有个情况是否能兼顾到而且避免?,
    如:
    tag.attrs.get("style", [])
    或者
    tag.attrs.get("class")
    有些标签是没有 clss 或者 style 属性的,get 会有 None ,None 不能 iterable ,就异常了。。。
    TypeError: argument of type 'NoneType' is not iterable
    deplivesb
        5
    deplivesb  
       Jun 7, 2023
    @pppguest3962 get 的第二个参数不是默认值?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1121 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 23:22 · PVG 07:22 · LAX 16:22 · JFK 19:22
    ♥ Do have faith in what you're doing.