这篇文章将跟大家分享Python网络爬虫中另一个强大的第三方网页请求库–requests库的一些基本用法。
requests库是对urllib请求库的再次封装,从而使得网络请求变得更加容易。
requests库包含的主要方法
requests包含有get(), post(), delete(), head(), requests()等七个方法。但我们平时一般只会用到get()和post()两个主要方法。
- get(url, params={key: value}, args) – 用于发送GET请求到特定的url。
参数 | 描述 |
---|---|
url | Required. The url of the request. |
params | Optional. A dictionary, list of tuples or bytes to send as a query string. Default None |
allow_redirects | Optional. A Boolean to enable/disable redirection. Default True (allowing redirects) |
auth | Optional. A tuple to enable a certain HTTP authentication. Default None |
cert | Optional. A String or Tuple specifying a cert file or key. Default None |
cookies | Optional. A dictionary of cookies to send to the specified url. Default None |
headers | Optional. A dictionary of HTTP headers to send to the specified url. Default None |
proxies | Optional. A dictionary of the protocol to the proxy url. Default None |
stream | Optional. A Boolean indication if the response should be immediately downloaded (False) or streamed (True). Default False |
timeout | Optional. A number, or a tuple, indicating how many seconds to wait for the client to make a connection and/or send a response. Default None which means the request will continue until the connection is closed |
verify | Optional. A Boolean or a String indication to verify the servers TLS certificate or not. Default True |
- post(url,data={key: value},json={key: value},args) – 用于发送POST请求到特定的url。
参数 | 描述 |
---|---|
url | Required. The url of the request |
data | Optional. A dictionary, list of tuples, bytes or a file object to send to the specified url |
json | Optional. A JSON object to send to the specified url |
files | Optional. A dictionary of files to send to the specified url |
allow_redirects | Optional. A Boolean to enable/disable redirection. Default True (allowing redirects) |
auth | Optional. A tuple to enable a certain HTTP authentication. Default None |
cert | Optional. A String or Tuple specifying a cert file or key. Default None |
cookies | Optional. A dictionary of cookies to send to the specified url. Default None |
headers | Optional. A dictionary of HTTP headers to send to the specified url. Default None |
proxies | Optional. A dictionary of the protocol to the proxy url. Default None |
stream | Optional. A Boolean indication if the response should be immediately downloaded (False) or streamed (True). Default False |
timeout | Optional. A number, or a tuple, indicating how many seconds to wait for the client to make a connection and/or send a response. Default None which means the request will continue until the connection is closed |
verify | Optional. A Boolean or a String indication to verify the servers TLS certificate or not. Default True |
基本GET请求
网页请求中最常见的就是GET请求,下面我们来了解下怎么使用requests来发起网络请求吧。下面的例子,我们通过requests的get()方法来完成对请求www.google.com 网页的请求。
1 | import requests |
如果我们想要传入参数,应该怎么办呢?比如我们现在想要添加参数q它的值为python,应该如下表示:
1 | import requests |
添加headers
因为很多网站都添加了反爬机制,如果我们传递header来模仿浏览器来登录,请求就会遭到拒绝。比如上面的例子中,如果我们把www.google.com 换为 www.zhihu.com 或者 www.movie.douban.com 都会遭到拒绝。下面我们一起通过来看下面的例子来了解一下如何添加header,从而解决此类问题吧。
1 | import requests |
抓取网页
下面我们来以抓取某瓣的电影排行榜来演示下怎么抓取网页内容。首先,我们将网页的html格式输出出来,然后方便我们进一步来查看我们所需要找的电影名的规律。
1 | import requests |
html格式输出之后,我们截取一部分内容如下:
1 | <li> |
我们会发现电影名位于<li> –> <div class=”info”> –> <span class=”title”>肖申克的救赎</span>这里面。然后,我们就可以利用正则表达式来筛选出所有的电影名。正则表达式的具体用法可以参照如下资料:
另外,因为每个网页只能存放10个电影,我们就需要做一个循环来提取所有的相关网页,具体代码如下:
1 | import requests |
运行之后,我们应该就会发现某瓣评分前250的电影名称被成功抓取了。
1 | ['肖申克的救赎', '霸王别姬', '阿甘正传', '泰坦尼克号', '这个杀手不太冷', '美丽人生', '千与千寻', '辛德勒的名单', '盗梦空间', '星际穿越', '忠犬八公的故事', '楚门的世界', '海上钢琴师', '三傻大闹宝莱坞', '机器人总动员', '放牛班的春天', '无间道', '疯狂动物城', '大话西游之大圣娶亲', '熔炉', '控方证人', '教父', '当幸福来敲门', '触不可及', '怦然心动', '龙猫', '末代皇帝', '寻梦环游记', '蝙蝠侠:黑暗骑士', '活着', '哈利·波特与魔法石', '指环王3:王者无敌', '乱世佳人', '素媛', '飞屋环游记', '我不是药神', '摔跤吧!爸爸', |
抓取图片
上面的例子中,我们抓取的是相关文字。当遇到图片、音频、以及影视资料的时候,我们又应该如何抓取呢?还是以某瓣为例,如果我们想要抓取电影的相关图片,首先要提取图片对应的二进制码。我们首先找到其中一个图片对应的url地址,然后利用Response的content属性就可以将图片的二进制码输出出来。
1 | import requests |
接下来我们将图片保存下来:
1 | import requests |
POST请求
requests库最常用两个方法是GET()和POST(),前面我们已经了解了GET()的请求方式,接下来我们再来看一下如何使用POST()。
1 | import requests |
运行之后,其返回结果如下:
1 | 200 |
响应值为200,说明已经成功请求。另外,我们也可以在结果的form一项中也发现已经成功提交{“query”: “hello”}的表单数据。