【Python爬虫】Requests的使用(3)

写在前面

这是第三篇介绍爬虫基础知识的文章,

前文回顾:

【Python爬虫】初识爬虫(1)

【Python爬虫】Urllib的使用(2)

今天主要给大家介绍Requests的使用。

/ 01 / 什么Requests?

Requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库。它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求。

因为是第三方库,所以使用前需要cmd安装:
pip install requests
安装完成后import一下,正常则说明可以开始使用了,当然还有更懒的方法通过IDE安装,比如pycharm。

/ 02 / 发送请求

普通请求

我们以get请求为例,首先要导入 Requests 模块:

1import requests

然后尝试获取百度页面:

1r=requests.get("https://www.baidu.com/")

现在,我们有一个名为r的 Response 对象,我们可以从这个对象中获取任何我们想要的信息。Requests简便的API意味着所有HTTP请求类型都是显而易见的,其他方法都是统一的接口样式。比如下面的例子:

1requests.get("https://www.baidu.com") #GET请求
2requests.post("https://www.baidu.com/post") #POST请求
3requests.put("https://www.baidu.com/put") #PUT请求
4requests.delete("https://www.baidu.com/delete") #DELETE请求
5requests.head("https://www.baidu.com/get") #HEAD请求
6requests.options("https://www.baidu.com/get") #OPTIONS请求


带参数的请求
还是以get请求为例,第一种是将参数放在URL当中:

1import requests
2
3r = requests.get("http://httpbin.org/get?name=gemey&age=22")
4print(r.text)

第二种先将参数填写在dict中,发起请求时params参数指定为dict:

1import requests
2
3kw={"wd":"ahab"}
4url="http://www.baidu.com/s?"
5r=requests.get(url,params=kw)
6print(r.status_code)
7print(r.request.url)

/ 03 / Response对象

使用requests方法后,会返回一个response对象,其存储了服务器响应的具体内容,我们以响应状态码为例:

1import requests
2
3r = requests.get("http://httpbin.org/")
4print(r.status_code)

输出的值为200,表示我们已经正常的请求到这个网站。我们再来看一下其他的响应:

1import requests
2
3response = requests.get('http://www.baidu.com')
4print(response.status_code)  # 打印状态码
5print(response.url)          # 打印请求url
6print(response.headers)      # 打印头信息
7print(response.cookies)      # 打印cookie信息
8print(response.text)         #以文本形式打印网页源码
9print(response.content)      #以字节流形式打印

/ 04/ Handler

跟Urllib设置代理方法相似,我们直接看下面的例子

1import requests
2
3proxies={"http":"http://163.177.151.23:80"}
4headers = {
5    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36"}
6r=requests.get("http://www.baidu.com",proxies=proxies,headers=headers)
7print(r.status_code)

除了基本的HTTP代理,Request还支持SOCKS协议的代理。这是一个可选功能,若要使用,你需要安装第三方库:

1pip install requests[socks]

使用方法跟使用HTTP代理一样简单。

1proxies = {
2    'http': 'socks5://user:pass@host:port',
3    'https': 'socks5://user:pass@host:port'
4}


上篇文章中提到我们可以使用IP池增强我们爬虫的健壮性,那么在我们组成的代理池中,如何随机选择代理ip,让使用次数较少的ip地址有更大的可能性被用到?
1.{"ip":ip,"times":0}
2.[{},{},{},{},{}],对这个ip的列表进行排序,按照使用次数进行排序
3.选择使用次数较少的10个ip,从中随机选择一个
 

/ 05/ Cookie&Session

关于什么是cookie和session想必大家都比较清楚,现在请思考这样一个问题:获取需要登陆后的页面有几种方法?

1.实例化session,使用session发送post请求,使用他获取登陆后的页面。
2.headers中添加cookie键值为cookie的字符串。
3.请求方法中添加cookies参数,接收字典形式的cookie,字典形式的cookie中的键是cookie的name,值是cookievalue。

我们以session为例:
request提供了一个一个叫做session的类,来实现客户端和服务端的会话保持
使用方法:
    实例化一个session对象
    让session发送get或post请求
   再使用session访问只有登录之后才能访问的网站,这时候session会自动带上服务器保存在其中的信息进行访问。
 

1session=request.session()  #实例化session对象
2response=session.get(url,header) #使用session对象发送get请求 就能获取服务端设置的session对象

/ 06/ 小试牛刀

实现任意贴吧的爬虫,保存网页到本地

 1class TiebaSpider:
 2    def __init__(self,tieba_name):
 3        self.tieba_name=tieba_name
 4        self.url_temp="https://tieba.baidu.com/f?kw="+tieba_name+"&ie=utf-8&pn={}"
 5        self.headers={"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36"}
 6
 7    def get_url_list(self):
 8        url_list=[]
 9        for i in range(1000):
10            url_list.append(self.url_temp.format(i*50))
11        return url_list
12    #return [self.url_temp.format(i*50)for i in range (1000)]
13    def parse_url(self,url):
14        print(url)
15        response=requests.get(url,headers=headers)
16        return  response.content.decode()
17    def save_html(self,html_str,page_num):
18        file_path="{} 第{}页".format(self.tieba_name,page_num)
19        with open(file_path,"w",encoding="utf-8")as f:
20            f.write(html_str)
21
22    def run(self):#实现主要逻辑
23        #1.构造url列表
24        url_list=self.get_url_list()
25        #2.遍历发送请求 获取响应
26        for url in url_list:
27            html_str=self.parse_url(url)
28        #3.保存
29            page_num=url_list.index(url)+1
30            self.save_html(html_str,page_num)
31
32if __name__ =='__main__':
33    TiebaSpider=TiebaSpider("NBA")
34    TiebaSpider.run()

官方文档:
requests的官方指南文档:
http://docs.python-requests.org/en/latest/user/quickstart.htm
requests的高级指南文档:
http://docs.python-requests.org/en/latest/user/advanced.html#advanced

猜你喜欢

转载自blog.csdn.net/sinat_34576567/article/details/86703971
今日推荐