Urllib库
Posted cangshuchirou
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Urllib库相关的知识,希望对你有一定的参考价值。
urllib是一个包,这个包收集了几个用于处理URLs的模块
urllib.request 用于打开和读取URLs urllib.error 用于触发请求的异常 urllib.parse 用于分析URLs urllib.robotparser 用于分析robots.txt格式的文件
URLOPEN练习
import urllib.request response = urllib.request.urlopen("http://www.baidu.com") print(response.read().decode("utf-8"))
import urllib.request import urllib.parse data = bytes(urllib.parse.urlencode({"word":"hello"}),encoding="utf8") response = urllib.request.urlopen("http://httpbin.org/post",data=data) print(response.read())
import urllib.request response = urllib.request.urlopen("http://httpbin.org/get",timeout=1) print(response.read())
import socket import urllib.request import urllib.error try: response = urllib.request.urlopen("http://httpbin.org/get",timeout=0.1) except urllib.error.URLError as e: if isinstance(e.reason,socket.timeout): print("TIME OUT")
响应练习
import urllib.request response = urllib.request.urlopen("https://www.python.org") print(type(response))
import urllib.request response = urllib.request.urlopen("https://www.python.org") print(response.status) print(response.getheaders()) print(response.getheader("Server"))
import urllib.request request = urllib.request.Request("https://www.python.org") response = urllib.request.urlopen(request) print(response.read().decode("utf-8"))
以上是关于Urllib库的主要内容,如果未能解决你的问题,请参考以下文章