urlib库的使用

urlib库实际上不是很常用,因为其api调用复杂,已被requests模块取代。

1.request发送请求

from urllib import request
#默认指定的是get请求
#urlopen可以指定data,设置了这个值,那么将变成post请求
response=request.urlopen('http://www.baidu.com')
# print(response)
#返回值:返回值是一个http.client.HTTPResponse对象,有read,readline,readlines以及getcode等方法
# print(response.read())
#读取前10个字节
# print(response.read(10))
#readline读取一行
# print(response.readline())
#readlines(),读取整个文件所有行,保存在一个列表变量中,每行作为一个元素,但读取大文件比较占内存
print(response.readlines())
#获取响应的状态码
# print(response.getcode())
View Code

2.request进行下载

from urllib import request
#下载网页内容,第一个参数指定url,第二个参数指定要写入哪个文件的文件名
# request.urlretrieve('http://www.baidu.com','baidu.html')
request.urlretrieve('https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=3478835771,1633744087&fm=26&gp=0.jpg','luban.jpg')
View Code

3.request的编码与解码

这个主要是针对url的

from urllib import parse
from urllib import request


#urlencode函数的用法
# params={'name':'张三','age':18,'great':'hello world'}
#传一个字典
# result=parse.urlencode(params)
# print(result)


# url='http://www.baidu.com/s'
# params={'wd':'蔡徐坤'}
# params=parse.urlencode(params)
# print(params)
# url=url+'?'+params
# response=request.urlopen(url)
# print(response.read())

#parse_qs函数的用法    解码
params={'name':'张三','age':18,'great':'hello world'}
qs=parse.urlencode(params)
print(qs)
result=parse.parse_qs(qs)
print(result)
View Code

4.将url进行分割的功能

from urllib import request
from urllib import parse

url='http://www.baidu.com/s?wd=python&username=lqz#1'
# result=parse.urlparse(url)
# print(result)
#有时候拿到一个url,想要对这个url中的各个组成部分进行分割,那么这时候就可以使用urlparse或urlsplit来进行分割
# print('scheme:',result.scheme)
# print('netloc:',result.netloc)
# print('path:',result.path)
# print('params:',result.params)
# print('query:',result.query)
# print('fragment:',result.fragment)

#fragment锚点
#urlsplit和urlparse的区别是urlsplit不会分割出params,以后使用的时候随便用哪个
#params用到的很少
#urlparse可以获取分号后的hello
url2='http://www.baidu.com/s;hello?wd=python&username=lqz#1'
print(parse.urlparse(url2))

result=parse.urlsplit(url)
print(result)
print(result.scheme)
print(result.netloc)
View Code

5.使用代理

from urllib import request

#7-ProxyHandler处理器
#通过ProxyHandler来设置使用代理服务器,防止同一ip访问网站次数过多被封禁
#常用的代理有:西刺,快代理,代理云
#httpbin.org专门测试http请求的,http://httpbin.org/ip 显示当前ip

#没有使用代理的本机IP
url='http://httpbin.org/ip'
# resp=request.urlopen(url)
# print(resp.read())

#使用代理的
#1.使用ProxyHandler传入代理构建一个handler
#2.使用上面创建的handler构建一个opener
#3.使用opener去发送一个请求


#使用代理
#传入一个字典
handler=request.ProxyHandler({'http':'60.2.44.182:46534'})
opener=request.build_opener(handler)
resp=opener.open(url)
print(resp.read())
View Code

6.携带cookie登录

from urllib import request


#HTTP无状态协议,是指协议对于交互性场景没有记忆能力。
#参数含义
#NAME:cookie的名字
#VALUE:cookie的值
#Expires:cookie的过期时间
#Path:cookie作用的路径
#Domain:cookie作用的域名。设置的cookie默认只在主域名起作用,要设置子域名也起作用,要加这个。
#SECURE:是否只在https协议下起作用



#使用cookie模拟登陆
from urllib import request
#老师人人网账户
email='970138074@qq.com'
password='pythonspider'



url='http://www.renren.com/880151247/profile'
#不使用cookie
# headers={
#     'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36',
#
# }
# req=request.Request(url=url,headers=headers)
# resp=request.urlopen(url)
# with open('renren.html','w',encoding='utf-8') as f:
#     f.write(resp.read().decode('utf-8'))


#使用cookie,这样做太麻烦了,还有其他办法
# headers={
#     "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
#     "Cookie":"anonymid=ju1t9qsph90pys; depovince=GW; _r01_=1; JSESSIONID=abcXfLxdWqMHi6Pe3ALNw; ick_login=e10e1e18-39d2-4e5c-a8b8-b90e4675fe8d; t=0ee4fa42a5f337b7e6368ed4f71ab8189; societyguester=0ee4fa42a5f337b7e6368ed4f71ab8189; id=970296329; xnsid=1a888270; jebecookies=f850bf5b-ecb9-40f2-b99e-541671612347|||||; ver=7.0; loginfrom=null; jebe_key=d6dba89f-a272-4afe-9157-347b5d152e41%7C49aae11d2fe745dc68a15c417d170403%7C1554333011073%7C1%7C1554333010402; wp_fold=0"
# }
# req=request.Request(url=url,headers=headers)
# resp=request.urlopen(url)
# with open('renren.html','w',encoding='utf-8') as f:
#     f.write(resp.read().decode('utf-8'))


from http.cookiejar import CookieJar

'''
CookieJar:管理HTTP cookie值,存储HTTP请求生成的cookie、向传出的HTTP请求添加cookie对象。
整个cookie都存储在内存中,对CookieJar实例进行垃圾回收后cookie也将丢失
'''

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36',
}
#模拟登陆
def get_opener():
    #创建一个cookiejar对象
    cookiejar=CookieJar()
    #使用cookiejar创建一个HTTPCookieJar对象
    handler=request.HTTPCookieProcessor(cookiejar)
    #使用上一步创建的handler创建一个opener
    opener=request.build_opener(handler)
    #使用opener发送登陆的请求(人人网的邮箱和密码)
    return opener

def login_renren(opener):

    data={
        'email':'970138074@qq.com',
        'password':'pythonspider'
    }
    from urllib import parse
    login_url='http://www.renren.com/ajaxLogin/login'
    req=request.Request(login_url,data=parse.urlencode(data).encode('utf-8'),headers=headers)
    opener.open(req)

def visit_profile(opener):
    #访问个人主页
    dapeng_url='http://www.renren.com/880151247/profile'

    req=request.Request(dapeng_url,headers=headers)
    resp=opener.open(req)
    with open('renren.html','w',encoding='utf-8') as f:
        f.write(resp.read().decode('utf-8'))


if __name__ == '__main__':
    opener=get_opener()
    login_renren(opener)
    visit_profile(opener)
View Code

7.cookie信息的加载与保存

from urllib import request

#保存cookie到本地
from http.cookiejar import MozillaCookieJar
#指定保存到哪个文件
cookiejar=MozillaCookieJar('cookie.txt')
handler=request.HTTPCookieProcessor(cookiejar)
opener=request.build_opener(handler)
# resp=opener.open('http://www.baidu.com')

#前面已经传了文件名,现在save不用传文件名。前面如果没传,则save要传文件名。每次写都会重新覆盖文件
# cookiejar.save()


#浏览器关闭,cookie过期的这种cookie是无法写入文件的。
resp=opener.open('http://httpbin.org/cookies/set?course=python')
# print(resp.read())
#ignore_discard即使cookie将被丢弃也保存,ignore_expires即使cookie将过期也进行保存
cookiejar.save(ignore_discard=True,ignore_expires=True)

#load  重用cookie信息,从本地loadcookie信息。要指定文件名,前面创建cookiejar的时候指定了文件名,则不用传

for cookie in cookiejar:
    print(cookie)
View Code

 

posted @ 2019-04-29 01:53  徐大  阅读(496)  评论(0编辑  收藏  举报