urllib库详解

1

1

urlopen函数

import urllib
# get请求
response = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))
# push请求
data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf-8')
response = urllib.request.urlopen('http://www.baidu.com', data=data)

响应

print(type(response))
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))

Request

r = urllib.request.Request('http://www.baidu.com', headers={}, data=None)
r.add_header(key='name', val='xiligey')  # 添加补充头部信息
response = urllib.request.urlopen(r)

Handler(辅助工具)

代理(ProxyHandler)

proxy_handler = urllib.request.ProxyHandler({
    'http': 'http://127.0.0.1:9743',
    'https': 'https://127.0.0.1:9999'
})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open('http://www.baidu.com')

cookie(验证用户身份用的)

cookie的获取


import http.cookiejar, urllib.request
cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')

for item in cookie:
    print(item.name+': '+item.value)
BAIDUID: ECF6F5566BD5FB90979D7A0D4651A227:FG=1
BIDUPSID: ECF6F5566BD5FB90979D7A0D4651A227
H_PS_PSSID: 1435_24565_21084_17001_20930
PSTM: 1510922402
BDSVRTM: 0
BD_HOME: 0

cookie的保存(请求时带上cookie[若尚未过期], 则可以保持登录状态)

import http.cookiejar, urllib.request
filename = 'cookie.txt'
cookie = http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True, ignore_expires=True)

另一种保存cookie的方式(和上面的格式不一样)

import http.cookiejar, urllib.request
filename = 'cookie.txt'
cookie = http.cookiejar.LWPCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True, ignore_expires=True)

读取本地的cookie文件(什么方式保存的cookie, 就用什么方式读取)

import http.cookiejar, urllib.request
cookie = http.cookiejar.LWPCookieJar()
cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
print(response.read().decode('utf-8'))

异常处理(主要看这两个类就差不多了)

  • urllib.error.URLError
    • 只有reason这一个属性
  • urllib.error.HTTPError(URLError的子类)
    有三个属性
    • code
    • reason
    • headers
import urllib
url = 'http://hehe.baidu.com'
try:
    response = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
    print(e.code, e.reason, e.headers)
except urllib.error.URLError as e:
    print(e.reason)
else:
    printn('Request Successfully')

url解析

urlparse

urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)

from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result))
print(result)

urlunparse(urlparse的反函数)

from urllib.parse import urlunparse
data = ['http', 'www.baidu.com', 'index.html', 'user', 'a=6', 'comment']
print(urlunparse(data))

urljoin(以后者为基准)

from urllib.parse import urljoin
print(urljoin('http://www.baidu.com', 'FAQ.html'))

urlencode(字典对象转化为get请求参数)

from urllib.parse import urlencode
params = {
    'name': 'germey',
    'age': 22
}
barse_url = 'http://www.baidu.com?'
url = barse_url + urlencode(params)
print(url)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值