使用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可以~
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
你倒是说明一下哪里不一样啊?
更新:
这是 QQ网页使用编码不规范的原因。
js代码里夹杂着不同编码的字符。
可能是复制粘贴惹的祸~
而,requests 比 urllib 容错能力更强些,把内容解析出来了。
给urllib加上一句:
html=html.decode('gb2312',errors='ignore')估计是默认的请求头不一样