Python urllib库和requests库

1. Python3 使用urllib库请求网络

1.1 基于urllib库的GET请求

请求百度首页www.baidu.com ,不添加请求头信息:

 1 import urllib.requests
 2
 3
 4 def get_page():
 5   url = ‘http://www.baidu.com/‘
 6   res = urllib.request.urlopen(url=url)
 7   page_source = res.read().decode(‘utf-8‘)
 8   print(page_source)
 9
10
11 if __name__ == ‘__main__‘:
12   get_page()

输出显示百度首页的源码。但是有的网站进行了反爬虫设置,上述代码可能会返回一个40X之类的响应码,因为该网站识别出了是爬虫在访问网站,这时需要伪装一下爬虫,让爬虫模拟用户行为,给爬虫设置headers(User-Agent)属性,模拟浏览器请求网站。

1.2 使用User-Agent伪装后请求网站

由于urllib.request.urlopen() 函数不接受headers参数,所以需要构建一个urllib.request.Request对象来实现请求头的设置:

 1 import urllib.request
 2
 3
 4 def get_page():
 5   url = ‘http://www.baidu.com‘
 6   headers = {
 7     ‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36‘
 8   }
 9   request = urllib.request.Request(url=url, headers=headers)
10   res = urllib.request.urlopen(request)
11   page_source = res.read().decode(‘utf-8‘)
12   print(page_source)
13
14
15 if __name__ == ‘__main__‘:
16   get_page()

添加headers参数,来模拟浏览器的行为。

1.3 基于urllib库的POST请求,并用Cookie保持会话

登陆ChinaUnix论坛,获取首页源码,然后访问一个文章。首先不使用Cookie看一下什么效果:

 1 import urllib.request
 2 import urllib.parse
 3
 4
 5 def get_page():
 6   url = ‘http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LcN2z‘
 7   headers = {
 8     ‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36‘
 9   }
10   data = {
11     ‘username‘: ‘StrivePy‘,
12     ‘password‘: ‘XXX‘
13   }
14   postdata = urllib.parse.urlencode(data).encode(‘utf-8‘)
15   req = urllib.request.Request(url=url, data=postdata, headers=headers)
16   res = urllib.request.urlopen(req)
17   page_source = res.read().decode(‘gbk‘)
18   print(page_source)
19
20   url1 = ‘http://bbs.chinaunix.net/thread-4263876-1-1.html‘
21   res1 = urllib.request.urlopen(url=url1)
22   page_source1 = res1.read().decode(‘gbk‘)
23   print(page_source1)
24
25
26 if __name__ == ‘__main__‘:
27   get_page()

搜索源码中是否能看见用户名StrivePy,发现登陆成功,但是再请求其它文章时,显示为游客状态,会话状态没有保持。现在使用Cookie看一下效果:

 1 import urllib.request
 2 import urllib.parse
 3 import http.cookiejar
 4
 5
 6 def get_page():
 7   url = ‘http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LcN2z‘
 8   headers = {
 9     ‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36‘
10   }
11   data = {
12     ‘username‘: ‘StrivePy‘,
13     ‘password‘: ‘XXX‘
14   }
15   postdata = urllib.parse.urlencode(data).encode(‘utf-8‘)
16   req = urllib.request.Request(url=url, data=postdata, headers=headers)
17   # 创建CookieJar对象
18   cjar = http.cookiejar.CookieJar()
19   # 以CookieJar对象为参数创建Cookie
20   cookie = urllib.request.HTTPCookieProcessor(cjar)
21   # 以Cookie对象为参数创建Opener对象
22   opener = urllib.request.build_opener(cookie)
23   # 将Opener安装位全局,覆盖urlopen函数,也可以临时使用opener.open()函数
24   urllib.request.install_opener(opener)
25   res = urllib.request.urlopen(req)
26   page_source = res.read().decode(‘gbk‘)
27   print(page_source)
28
29   url1 = ‘http://bbs.chinaunix.net/thread-4263876-1-1.html‘
30   res1 = urllib.request.urlopen(url=url1)
31   page_source1 = res1.read().decode(‘gbk‘)
32   print(page_source1)
33
34
35 if __name__ == ‘__main__‘:
36   get_page()

结果显示登陆成功后,再访问其它文章时,显示为登陆状态。若要将Cookie保存为文件待下次使用,可以使用MozillaCookieJar对象将Cookie保存为文件。

 1 import urllib.request
 2 import urllib.parse
 3 import http.cookiejar
 4
 5
 6 def get_page():
 7     url = ‘http://bbs.chinaunix.net/member.php?mod=logging&action=login&loginsubmit=yes&loginhash=LcN2z‘
 8     headers = {
 9         ‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36‘
10     }
11     data = {
12         ‘username‘: ‘StrivePy‘,
13         ‘password‘: ‘XXX‘
14     }
15     postdata = urllib.parse.urlencode(data).encode(‘utf-8‘)
16     req = urllib.request.Request(url=url, data=postdata, headers=headers)
17     filename = ‘cookies.txt‘
18     # 创建CookieJar对象
19     cjar = http.cookiejar.MozillaCookieJar(filename)
20     # 以CookieJar对象为参数创建Cookie
21     cookie = urllib.request.HTTPCookieProcessor(cjar)
22     # 以Cookie对象为参数创建Opener对象
23     opener = urllib.request.build_opener(cookie)
24     # 临时使用opener来请求
25     opener.open(req)
26     # 将cookie保存为文件
27     cjar.save(ignore_discard=True, ignore_expires=True)

会在当前工作目录生成一个名为cookies.txtcookie文件,下次就可以不用登陆(如果cookie没有失效的话)直接读取这个文件来实现免登录访问。例如不进行登陆直接访问其中一篇文章(没登陆也可以访问,主要是看抬头是不是登陆状态):

 1 import http.cookiejar
 2
 3
 4 def get_page():
 5     url1 = ‘http://bbs.chinaunix.net/thread-4263876-1-1.html‘
 6     filename = ‘cookies.txt‘
 7     cjar = http.cookiejar.MozillaCookieJar(filename)
 8     cjar.load(ignore_discard=True, ignore_expires=True)
 9     cookie = urllib.request.HTTPCookieProcessor(cjar)
10     opener = urllib.request.build_opener(cookie)
11     res1 = opener.open(url1)
12     page_source1 = res1.read().decode(‘gbk‘)
13     print(page_source1)
14
15
16 if __name__ == ‘__main__‘:
17     get_page()

结果显示是以登陆状态在查看这篇文章。

原文地址:https://www.cnblogs.com/strivepy/p/9231127.html

时间: 2024-08-26 08:14:28

Python urllib库和requests库的相关文章

python简洁之道-----Requests库

requests是python的一个HTTP客户端库,和urllib.urllib2类似,但是urllib2的api比较复杂,比如像实现一个post或是get功能都得需要一大堆代码. 今天先简单介绍一下这个库,等我看过官方文档之后,在写一个全面一点的. # -*- coding:utf8 -*- import request r = requests.get('http://www.zhidaow.com')#发送请求 r.status_code#返回状态码 r.headers['content

python网络爬虫之requests库

Requests库是用Python编写的HTTP客户端.Requests库比urlopen更加方便.可以节约大量的中间处理过程,从而直接抓取网页数据.来看下具体的例子: def request_function_try():     headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0'}     r=requests.get(url="http://www

请求库之requests库

目录 介绍 基于GET请求 1.基本请求 2.带参数的GET请求->params 带参数的GET请求->headers 带参数的GET请求->cookie 基于POST请求 1.介绍 2.发送post请求,模拟浏览器的登录行为 requests.session()自动帮我们保存cookie信息 补充 响应response respone属性 获取二进制数据 爬取大文件 解析json数据 SSL Cert Verification 使用代理 超时设置 异常处理 上传文件 介绍 #介绍:使用

python requests库学习笔记(上)

尊重博客园原创精神,请勿转载! requests库官方使用手册地址:http://www.python-requests.org/en/master/:中文使用手册地址:http://cn.python-requests.org/zh_CN/latest/: requests库作者Kenneth Reitz个人主页:https://www.kennethreitz.org/: requests库github地址:https://github.com/requests/requests: requ

requests库和urllib包对比

python中有多种库可以用来处理http请求,比如python的原生库:urllib包.requests类库.urllib和urllib2是相互独立的模块,python3.0以上把urllib和urllib2合并成一个库了,requests库使用了urllib3.requests库的口号是"HTTP For Humans",为人类使用HTTP而生,用起来不知道要比python原生库好用多少呢,比起urllib包的繁琐,requests库特别简洁和容易理解.话不多说,代码为证~~~ 下

异步请求Python库 grequests的应用和与requests库的响应速度的比较

requests库是python一个优秀的HTTP库,使用它可以非常简单地执行HTTP的各种操作,例如GET.POST等.不过,这个库所执行的网络请求都是同步了,即cpu发出请求指令后,IO执行发送和等待等操作,在这段IO执行的时间里,cpu什么也不做,这样cpu的计算能力就被浪费了.所以,可以尝试把网络请求修改为异步的,也就是在IO发挥作用的这段时间,CPU去做这个程序里的其他事情,等IO收到响应的数据,CPU回来处理.偶然发现下面的帖子特分享与大家,并与requests库进行简单响应速度比较

python Requests库总结

什么是Requests库? requests库github地址:https://github.com/requests/requests Reqyests库主要用来准备Request和处理Response. 为什么要学习Requests库? web开发和爬虫都需要学习的东西,在服务端编程中理解好Requests库可以更好的编写Restful API的程序,还是自动化测试的工具箱. 安装Requests库 pip install requests 这个是安装requests库的 pip insta

Requests库详解

urllib库作为基本库,requests库也是在urllib库基础上发展的 但是urllib在使用上不如requests便利,比如上篇文章在写urllib库的时候,比如代理设置,处理cookie时,没有写,因为感觉比较繁琐,另外在发送post请求的时候,也是比较繁琐. 一言而代之,requests库是python实现的简单易用的HTTP库 在以后做爬虫的时候,建议用requests,不用urllib 用法讲解: #!/usr/bin/env python # -*- coding:utf-8

网络爬虫入门:你的第一个爬虫项目(requests库)

0.采用requests库 虽然urllib库应用也很广泛,而且作为Python自带的库无需安装,但是大部分的现在python爬虫都应用requests库来处理复杂的http请求.requests库语法上简洁明了,使用上简单易懂,而且正逐步成为大多数网络爬取的标准. 1. requests库的安装采用pip安装方式,在cmd界面输入: pip install requests 小编推荐一个学python的学习qun 491308659 验证码:南烛无论你是大牛还是小白,是想转行还是想入行都可以来