Python中关于urllib.request.urlopen方法的使用问题
import urllib.request
def download(url):
print(“DOWNLOADING:”,url)
try:
html=urllib.request.urlopen(url).read()
print(html)
except Exception as e:
print(“DOWNLOAD ERROR:”,e)
html=None
return html
download(“http://www.ccb.com/”)
上面的代码输出如下:
DOWNLOADING: http://www.ccb.com/
b’<SCRIPT LANGUAGE=“JavaScript”>\n window.location="/cn/home/indexv3.html";\n</SCRIPT>\n\n\n’
请问,这个 html 的输出从网页的源码中是找不到的,为何 html 输出后会是这样的内容?谢谢!
Python中关于urllib.request.urlopen方法的使用问题
➜ ~ curl http://www.ccb.com/
<SCRIPT LANGUAGE=“JavaScript”>
window.location="/cn/home/indexv3.html";
</SCRIPT>
没毛病
问题核心: urllib.request.urlopen 是Python标准库中用于发起HTTP/HTTPS请求的基础函数,但使用时经常遇到编码、异常处理、请求头设置等问题。
主要用法和常见问题:
-
基本GET请求:
import urllib.request import urllib.error try: response = urllib.request.urlopen('https://httpbin.org/get') data = response.read() # 获取bytes类型响应体 print(data.decode('utf-8')) # 通常需要解码 except urllib.error.URLError as e: print(f"请求失败: {e.reason}") -
处理POST请求(需要传递data参数):
import urllib.parse import urllib.request post_data = urllib.parse.urlencode({'key1': 'value1', 'key2': 'value2'}).encode() req = urllib.request.Request('https://httpbin.org/post', data=post_data) response = urllib.request.urlopen(req) -
设置请求头:
headers = {'User-Agent': 'Mozilla/5.0'} req = urllib.request.Request('https://httpbin.org/headers', headers=headers) response = urllib.request.urlopen(req) -
关键注意事项:
- 返回值:
urlopen()返回一个http.client.HTTPResponse对象,需要调用.read()方法获取响应内容(bytes类型)。 - 编码问题:响应内容需要根据实际编码(如
utf-8、gbk)进行解码,可通过response.headers.get_content_charset()获取编码信息。 - 异常处理:务必捕获
urllib.error.URLError和urllib.error.HTTPError。 - 简单场景适用:
urllib.request适合简单请求,复杂场景(如会话保持、连接池)建议使用第三方库requests。
- 返回值:
总结建议: 对于简单HTTP请求,urlopen() 够用,但记得处理编码和异常;复杂需求直接上 requests 库更省心。
我倒是没说这个结果有错,我只是不理解这个 html 是个什么东西,为何是显示这些内容,并且这个字符串其实并不存在于这个网页的源代码中
那个是 js,你要等 js 加载完才能访问到真正的网页,你应该访问这个地址 www.ccb.com/cn/home/indexv3.html
你获取的是一小段 JS 代码,让你跳转到他们的 indexv3.html 页面。不知道这么做的意义在哪。
访问 http://www.ccb.com 时的默认网页源码就是你爬到的字符串内容。
通过浏览器访问到的页面是 http://www.ccb.com/cn/home/indexv3.html,那已经是重定向后的页面啦。
没学过 html 么。。
感谢大家指点,确实没有系统地学过 HTML
浏览器直接访问也是这个源码,然后浏览器会自动执行这个代码,跳转到那个新的页面。
但是你的 py 不会跳,因为他不执行这个跳转的 js

