推荐学习书目
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
xucuncicero
V2EX  ›  Python

一个关于 beautifulsoup 里面的 findAll 的使用问题

  •  
  •   xucuncicero · Sep 10, 2016 · 7369 views
    This topic created in 3568 days ago, the information mentioned may be changed or developed.

    我要解析的网页中同时存在

    <p class="left title"><a href="xxxx">xxxx</a></p>
    

    <p class="title"><a href="xxxx">xxxx</a></p>
    

    如果用

    soup.findAll('p', {'class': 'title'}):
    

    会同时输出上面两个 class ,我现在只想要"title",应该怎么写?

    8 replies    2016-09-11 11:24:17 +08:00
    assassinleo
        1
    assassinleo  
       Sep 10, 2016
    试试这个看行不: soup.find_all(‘ p ’,class="title")或者 soup.find_all(‘ p ’,class=re.compile("title"))

    ref: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all
    xucuncicero
        2
    xucuncicero  
    OP
       Sep 10, 2016
    @assassinleo 无效,只是写法不一样,后一个有语法错误(应该写成 class_),还有其他写法结果也没什么区别。

    这里的问题是 find_all 或者 findAll 的参数中只要能匹配到"title"就肯定能匹配到"left title",不知道有没有什么能排除某个字符串的写法。
    caspartse
        3
    caspartse  
       Sep 10, 2016   ❤️ 1
    soup.select('p[class=title]')
    xiahei
        4
    xiahei  
       Sep 10, 2016   ❤️ 1
    不一定就要用`find_all()`, `select()`也能用上。
    7sDream
        5
    7sDream  
       Sep 10, 2016   ❤️ 1
    http://7sdream-rikka-demo.daoapp.io/files/2016-09-10-919783703

    如果看不见图片就复制打开……

    我试了一下这样可以。

    希望有帮助。
    judyApple
        6
    judyApple  
       Sep 11, 2016   ❤️ 1
    加个 if 语句好像就可以。 itDic.attrs 返回一个字典,要字典的 value 长度为 1 就可以筛去 left
    for itDic in soup.findAll("p",{"class":"title"}):
    if len(itDic.attrs['class'])==1:
    print(itDic.attrs)
    aihimmel
        7
    aihimmel  
       Sep 11, 2016 via Android
    Xpath 大法好
    xucuncicero
        8
    xucuncicero  
    OP
       Sep 11, 2016
    @caspartse
    @xiahei
    @7sDream 多谢,简单高效

    @judyApple 同赞

    @aihimmel 看来得多学点东西了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2715 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 03:00 · PVG 11:00 · LAX 20:00 · JFK 23:00
    ♥ Do have faith in what you're doing.