python - 用urllib.request和requests请求同一网页,接着用beautifulsoup解析出来的为什么不一样呢?
问题描述
使用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可以~
你倒是说明一下哪里不一样啊?
更新:
这是 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])
这篇关于python - 用urllib.request和requests请求同一网页,接着用beautifulsoup解析出来的为什么不一样呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!