python 包中的 urllib 网络请求教程
目录
一、简介二、发起请求三、携带参数请求四、获取响应数据五、设置headers六、使用代理七、认证登录八、设置cookie九、异常处理十、HTTP异常十一、超时异常十二、解析编码十三、参数拼接十四、请求链接解析十五、拼接链接十六、字典转换参数一、简介
是一个 python 内置包,不需要额外安装即可使用urllib 是 Python 标准库中用于网络请求的库,内置四个模块,分别是urllib.request:用来打开和读取 url,可以用它来模拟发送请求,获取网页响应内容urllib.error:用来处理 urllib.request 引起的异常,保证程序的正常执行urllib.parse:用来解析 url,可以对 url 进行拆分、合并等urllib.robotparse:用来解析 robots.txt 文件,判断网站是否能够进行爬取二、发起请求
import urllib.request
# 方法一
resp = urllib.request.urlopen("http://www.baidu.com", timeout=1)
print(resp.read().decode("utf-8"))
# 方法二
request = urllib.request.Request("http://www.baidu.com")
response = urllib.request.urlopen(request)
print(response.read().decode("utf-8"))三、携带参数请求
请求某些网页时需要携带一些数据import urllib.parse
import urllib.request
params = {
"name":"autofelix",
"age":"25"
}
data = bytes(urllib.parse.urlencode(params), encoding="utf8")
response = urllib.request.urlopen("http://www.baidu.com/", data=data)
print(response.read().decode("utf-8"))四、获取响应数据
import urllib.request
resp = urllib.request.urlopen("http://www.baidu.com")
print(type(resp))
print(resp.status)
print(resp.geturl())
print(resp.getcode())
print(resp.info())
print(resp.getheaders())
print(resp.getheader("Server"))五、设置headers
import urllib.request
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
}
request = urllib.request.Request(url="http://tieba.baidu.com/", headers=headers)
response = urllib.request.urlopen(request)
print(response.read().decode("utf-8"))六、使用代理
import urllib.request
proxys = urllib.request.ProxyHandler({
"http": "proxy.cn:8080",
"https": "proxy.cn:8080"
})
opener = urllib.request.build_opener(proxys)
urllib.request.install_opener(opener)
request = urllib.request.Request(url="http://www.baidu.com/")
response = urllib.request.urlopen(request)
print(response.read().decode("utf-8"))七、认证登录
有些网站需要携带账号和密码进行登录之后才能继续浏览网页import urllib.request
url = "http://www.baidu.com/"
user = "autofelix"
password = "123456"
pwdmgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
pwdmgr.add_password(None,url,user,password)
auth_handler = urllib.request.HTTPBasicAuthHandler(pwdmgr)
opener = urllib.request.build_opener(auth_handler)
response = opener.open(url)
print(response.read().decode("utf-8"))八、设置cookie
如果请求的页面每次需要身份验证,我们可以使用Cookies 来自动登录,免去重复登录验证的操作
import http.cookiejar
import urllib.request
cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open("http://www.baidu.com/")
f = open("cookie.txt", "a")
for item in cookie:
f.write(item.name+" = "+item.value+"\n")
f.close()九、异常处理
from urllib import error, request
try:
resp = request.urlopen("http://www.baidu.com")
except error.URLError as e:
print(e.reason)十、HTTP异常
from urllib import error, request
try:
resp = request.urlopen("http://www.baidu.com")
except error.HTTPError as e:
print(e.reason, e.code, e.headers, sep="\n")
except error.URLError as e:
print(e.reason)
else:
print("request successfully")十一、超时异常
import socket, urllib.request, urllib.error
try:
resp = urllib.request.urlopen("http://www.baidu.com", timeout=0.01)
except urllib.error.URLError as e:
print(type(e.reason))
if isinstance(e.reason,socket.timeout):
print("time out")十二、解析编码
from urllib import parse
name = parse.quote("飞兔小哥")
# 转换回来
parse.unquote(name)十三、参数拼接
在访问url时,我们常常需要传递很多的url参数而如果用字符串的方法去拼接url的话,会比较麻烦from urllib import parse
params = {"name": "飞兔", "age": "27", "height": "178"}
parse.urlencode(params)十四、请求链接解析
from urllib.parse import urlparse
result = urlparse("http://www.baidu.com/index.html?user=autofelix")
print(type(result))
print(result)十五、拼接链接
如果拼接的是两个链接,则以返回后面的链接如果拼接是一个链接和参数,则返回拼接后的内容from urllib.parse import urljoin
print(urljoin("http://www.baidu.com", "index.html"))十六、字典转换参数
from urllib.parse import urlencode
params = {
"name": "autofelix",
"age": 27
}
baseUrl = "http://www.baidu.com?"
print(baseUrl + urlencode(params))到此这篇关于python 包中的 urllib 网络请求教程的文章就介绍到这了,更多相关 urllib 网络请求 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
X 关闭
X 关闭
- 15G资费不大降!三大运营商谁提供的5G网速最快?中国信通院给出答案
- 2联想拯救者Y70发布最新预告:售价2970元起 迄今最便宜的骁龙8+旗舰
- 3亚马逊开始大规模推广掌纹支付技术 顾客可使用“挥手付”结账
- 4现代和起亚上半年出口20万辆新能源汽车同比增长30.6%
- 5如何让居民5分钟使用到各种设施?沙特“线性城市”来了
- 6AMD实现连续8个季度的增长 季度营收首次突破60亿美元利润更是翻倍
- 7转转集团发布2022年二季度手机行情报告:二手市场“飘香”
- 8充电宝100Wh等于多少毫安?铁路旅客禁止、限制携带和托运物品目录
- 9好消息!京东与腾讯续签三年战略合作协议 加强技术创新与供应链服务
- 10名创优品拟通过香港IPO全球发售4100万股 全球发售所得款项有什么用处?

