V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 325 天前 · 595 次点击
    这是一个创建于 325 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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  
       325 天前   ❤️ 1
    results = soup.findAll(lambda tag: tag.attrs.get("class") == ["bts"] and tag.attrs.get("style") == "display:none")
    deplivesb
        2
    deplivesb  
       325 天前   ❤️ 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  
       325 天前   ❤️ 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
       324 天前
    @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  
       324 天前
    @pppguest3962 get 的第二个参数不是默认值?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2959 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 13:18 · PVG 21:18 · LAX 06:18 · JFK 09:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.