python - 用urllib.request和requests请求同一网页,接着用beautifulsoup解析出来的为什么不一样呢?
黄舟
黄舟 2017-04-18 09:33:27
[Python讨论组]

使用urllib.request的代码:
import urllib.request
from bs4 import BeautifulSoup

url="http://finance.qq.com/gdyw.htm"
head = {}
head['user_agent']='Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'

html=urllib.request.urlopen(url).read()
soup=BeautifulSoup(html,'lxml')
print(soup.prettify())

使用requests的代码:
import requests
from bs4 import BeautifulSoup

url = "http://finance.qq.com/gdyw.htm"
response = requests.get(url)
soup = BeautifulSoup(response.text,'lxml')
print(soup.prettify())


urllib.request没有解析到这一块内容,但是requests可以~

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(2)
阿神

你倒是说明一下哪里不一样啊?


更新:

这是 QQ网页使用编码不规范的原因。
js代码里夹杂着不同编码的字符。
可能是复制粘贴惹的祸~
而,requests 比 urllib 容错能力更强些,把内容解析出来了。
给urllib加上一句:
html=html.decode('gb2312',errors='ignore')

from bs4 import BeautifulSoup
url="http://finance.qq.com/gdyw.htm"

##使用urllib.request的代码:
import urllib.request
html=urllib.request.urlopen(url).read()
html=html.decode('gb2312',errors='ignore')
soup1=BeautifulSoup(html,'lxml')
lfls1 = str(soup1).split('<!-- 左侧列表 -->',2)

##使用requests的代码:
import requests
response = requests.get(url)
soup2 = BeautifulSoup(response.text,'lxml')
lfls2 = str(soup2).split('<!-- 左侧列表 -->',2)

print(lfls1[1][:500])
print('='*70)
print(lfls2[1][:500])
怪我咯

估计是默认的请求头不一样

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号