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
wisefree
V2EX  ›  Python

爬虫遇到的一点问题: BeautifulSoup 处理后的内容发生了变化

  •  
  •   wisefree · 2017-01-03 14:57:18 +08:00 · 2662 次点击
    这是一个创建于 2668 天前的主题,其中的信息可能已经有所发展或是发生改变。

    get 下来的内容,有 t_con 的字符的 但是呢?经过 BeautifulSoup 处理后,却没有了 t_con 的字符,这是怎么回事呢?

    
    # -*- coding: utf-8 -*-
    
    import requests
    from bs4 import BeautifulSoup
    
    def get_info_from(url):
        headers = {
            "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"
        }
    
        web_data = requests.get(url, headers=headers)
        web_data.encoding = 'utf-8'
        # print(web_data.text)    # 输出的结果中,搜索 t_con ,可以搜到
    
        soup = BeautifulSoup(web_data.text, 'lxml')
        # print(soup)     # 输出的结果中,搜索 t_con, 搜不到了,为什么经过处理后却搜索不到了呢?
    
    if __name__ == "__main__":
        test_url = "http://tieba.baidu.com/f?kw=%E4%B8%BA%E7%9F%A5%E7%AC%94%E8%AE%B0&ie=utf-8&pn=0"
        get_info_from(test_url)
    
    
    7 条回复    2017-01-04 09:22:08 +08:00
    yappa
        1
    yappa  
       2017-01-03 14:58:46 +08:00   ❤️ 1
    lxml 改成 html5lib 试一下
    wisefree
        2
    wisefree  
    OP
       2017-01-03 15:26:33 +08:00
    @yappa 用 html5lib 可以,但是为什么呢?
    cheeseleng
        3
    cheeseleng  
       2017-01-03 15:26:42 +08:00   ❤️ 1
    解析器对非标准的 html 格式的解析结果不一样, lxml 会忽略掉不符合规则的标签, html5lib 会自动补全不正确的
    wisefree
        4
    wisefree  
    OP
       2017-01-03 15:35:46 +08:00
    @cheeseleng 十分感谢!一直用 BeautifulSoup+lxml ,现在发现有些网页解析不好,而且 find_all 还找不出东西。这个时候是不是该换正则了
    cheeseleng
        5
    cheeseleng  
       2017-01-03 15:42:15 +08:00   ❤️ 1
    @wisefree 如果对正则很熟的话绝对换正则啊, beautifulsoup 和 xpath 只是比较方便,复杂的要求就懵逼了
    wisefree
        6
    wisefree  
    OP
       2017-01-03 15:52:12 +08:00
    @cheeseleng thanks !:)
    aidchow
        7
    aidchow  
       2017-01-04 09:22:08 +08:00 via Android
    @cheeseleng 学习了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5256 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 01:16 · PVG 09:16 · LAX 18:16 · JFK 21:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.