亲宝软件园·资讯

展开

urllib 网络请求

autofelix 人气:0

一、简介

二、发起请求

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

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)

十三、参数拼接

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))

加载全部内容

相关教程
猜你喜欢
用户评论