wisefree
V2EX  ›  Python

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

By wisefree at 2017 年 1 月 3 日 · 3606 次点击

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 年 1 月 3 日   ❤️ 1
lxml 改成 html5lib 试一下
wisefree
   2
wisefree  
OP
   2017 年 1 月 3 日
@yappa 用 html5lib 可以,但是为什么呢?
cheeseleng
   3
cheeseleng  
   2017 年 1 月 3 日   ❤️ 1
解析器对非标准的 html 格式的解析结果不一样, lxml 会忽略掉不符合规则的标签, html5lib 会自动补全不正确的
wisefree
   4
wisefree  
OP
   2017 年 1 月 3 日
@cheeseleng 十分感谢!一直用 BeautifulSoup+lxml ,现在发现有些网页解析不好,而且 find_all 还找不出东西。这个时候是不是该换正则了
cheeseleng
   5
cheeseleng  
   2017 年 1 月 3 日   ❤️ 1
@wisefree 如果对正则很熟的话绝对换正则啊, beautifulsoup 和 xpath 只是比较方便,复杂的要求就懵逼了
wisefree
   6
wisefree  
OP
   2017 年 1 月 3 日
@cheeseleng thanks !:)
aidchow
   7
aidchow  
   2017 年 1 月 4 日 via Android
@cheeseleng 学习了
推荐学习书目
› 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
© 2026 V2EX · 27ms · 3.9.8.5