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

2017-01-03 14:57:18 +08:00
 wisefree

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)

2666 次点击
所在节点    Python
7 条回复
yappa
2017-01-03 14:58:46 +08:00
lxml 改成 html5lib 试一下
wisefree
2017-01-03 15:26:33 +08:00
@yappa 用 html5lib 可以,但是为什么呢?
cheeseleng
2017-01-03 15:26:42 +08:00
解析器对非标准的 html 格式的解析结果不一样, lxml 会忽略掉不符合规则的标签, html5lib 会自动补全不正确的
wisefree
2017-01-03 15:35:46 +08:00
@cheeseleng 十分感谢!一直用 BeautifulSoup+lxml ,现在发现有些网页解析不好,而且 find_all 还找不出东西。这个时候是不是该换正则了
cheeseleng
2017-01-03 15:42:15 +08:00
@wisefree 如果对正则很熟的话绝对换正则啊, beautifulsoup 和 xpath 只是比较方便,复杂的要求就懵逼了
wisefree
2017-01-03 15:52:12 +08:00
@cheeseleng thanks !:)
aidchow
2017-01-04 09:22:08 +08:00
@cheeseleng 学习了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/331908

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX