小白学爬虫(二)-- requests库初使用

什么是requests库

Requests库是Python中的一个HTTP网络请求库,用来简化网络请求!

requests库的安装

如果在安装python的同时安装了pip,那么可以直接使用pip来进行安装。步骤是:

  • win+R 打开运行窗口
  • 输入 cmd 进入命令行
  • 输入 pip install requests
    至此,requests库安装成功

requests库的使用

爬取第一个网页

这里以 “http://www.baidu.com“为例。
第一步导入requests库

import requests

第二步创建一个url,这里是”http://www.baidu.com

url = "http://www.baidu.com"

第三步对”http://www.baidu.com“发起一个get请求

response = requests.get(url)

这里的response是一个对象,response 对象是服务器发送到客户端的数据,response的属性和方法后面会将
第四步可以调用response对象的方法将服务器端的数据打印一下

print(response.text)

这里返回的数据如下:

<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>ç™¾åº¦ä¸€ä¸‹ï¼Œä½ å°±çŸ¥é“</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ–°é—»</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

可以看到这里的数据是乱码,出现这种情况的原因是:response.text 的解码是根据HTTP头部对响应的编码做出有根据的推测,推测的文本编码。也就是说它的解码方式只是一种推测,并不一定正确。
那如何修改编码方式呢?
可以在打印之前增加一行:

response.enconding("utf-8")

这行的作用就是将编码格式改为 utf-8 编码,这对大多数网页来说都是可行的。
再次打印结果如下所示:

<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

到这里就把请求 “http://www.baidu.com” 返回的数据获取了。要注意这个数据并不是你点击“检查”->“elements”里面的东西。这一点在前文已经说过:小白学爬虫(一) – 基础知识。
下面给出完整代码

import requests

url = "http://www.baidu.com"
response = requests.get(url)
response.encoding = "utf-8"# 修改编码格式
print(response.text)        

在这个例子里面遇到了一个问题,就是使用 response.text 出现乱码问题;这个问题其实很常见,我们的解决方法是 使用reponse.encoding修改了编码格式。这个方法是可行的,另外还可以直接使用 print(reponse.content.decode(“utf-8”)) 直接解码。
于是代码就变成了这样:

import requests

url = "http://www.baidu.com"
response = requests.get(url)
print(response.content.decode())

结果不变。response.content.decode()如果不写参数,默认是 “utf-8”编码,如果使用”utf-8”解码出现问题,可以尝试 response.content.decode(“gbk”) 使用gbk解码。

获取网页源码的正确打开方式

总结一下获取网页源码的正确打开方式:

1,response.content.decode()
2, response.content.decode("gbk")
3, response.text

第一种也可以换成

response.encoding("utf-8")
print(response.text)

requests的reponse对象

reponse对象是爬虫发起请求时服务器返回的东西。

常见reponse方法

在上面那个例子里面加入

print(response.status_code)  # 结果是200
print(response.request.headers)

结果是:

{'User-Agent': 'python-requests/2.19.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}

加入

print(response.headers)

结果是:

{'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'Keep-Alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Wed, 01 Aug 2018 13:05:06 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:27:56 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'}

大家可以参考我前一篇文章或者自行百度这写东西是什么,另外一张图说明一下什么是请求头和响应头。
这里写图片描述

发送一个post请求(headers)

尝试用百度翻译翻译“一个人并不是生来就要给打败的,你尽可以消灭它,但就是打不败它”,在百度翻译中的结果是:“A man is not born to defeat. You can destroy it, but you can not defeat it.”
现在尝试用程序来实现。
这里写图片描述
这里写图片描述
首先,试一下能不能正确访问到百度翻译的页面

import requests

url = "http://fanyi.baidu.com/basetrans"

query_string = {"query":"一个人并不是生来就要给打败的,你尽可以消灭它,但就是打不败它",
"from":"zh",
"to":"en",}
reponse = requests.post(url,data = query_string)
print(reponse)  
print(reponse.content.decode())    

运行结果是:

<Response [200]>

post请求要提交数据,用程序来实现就是放在requests.post()的data参数中。可以看到我们提交的数据与浏览器是一样的,但是却并没有得到响应,只返回了一个状态码 200。这个状态吗的意思是一切都是ok的,但是我们没有接收到服务器返回来的数据呀。可能的情况是服务器已经发现了我们是一个爬虫,而不是一个浏览器。所以我们就要装的像一点,首先在程序里面加上headers。
这里写图片描述
将上面浏览器里面的headers附加到程序里就变成了

import requests

url = "http://fanyi.baidu.com/basetrans"
query_string = {"query":"一个人并不是生来就要给打败的,你尽可以消灭它,但就是打不败它",
"from":"zh",
"to":"en",}
m_headers = {
    "User-Agent":"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Mobile Safari/537.36"
}
reponse = requests.post(url,data = query_string,headers = m_headers)

print(reponse)  
print(reponse.content.decode())    

运行结果:

<Response [200]>
{"errno":0,"from":"zh","to":"en","trans":[{"dst":"A man is not born to defeat. You can destroy it, but you can not defeat it.","prefixWrap":0,"src":"\u4e00\u4e2a\u4eba\u5e76\u4e0d\u662f\u751f\u6765\u5c31\u8981\u7ed9\u6253\u8d25\u7684\uff0c\u4f60\u5c3d\u53ef\u4ee5\u6d88\u706d\u5b83\uff0c\u4f46\u5c31\u662f\u6253\u4e0d\u8d25\u5b83","relation":[],"result":[[0,"A man is not born to defeat. You can destroy it, but you can not defeat it.",["0|90"],[],["0|90"],["0|75"]]]}],"dict":[],"keywords":[{"means":["one"],"word":"\u4e00\u4e2a\u4eba"},{"means":["isn't","fault","blame","ain't","an't"],"word":"\u4e0d\u662f"},{"means":["have an instinct for"],"word":"\u751f\u6765\u5c31"},{"means":["beat","defeat","suffer a defeat","be defeated","vanquish"],"word":"\u6253\u8d25"},{"means":["can","may","passable","pretty good","Ok"],"word":"\u53ef\u4ee5"},{"means":["eliminate","perish","die out","annihilate","cut the throat of"],"word":"\u6d88\u706d"},{"means":["quite right","exactly","even if","even","namely"],"word":"\u5c31\u662f"},{"means":["unbeaten","undefeated","invincible"],"word":"\u4e0d\u8d25"}]}

可以看到在”dst”里面已经有了翻译的结果,和浏览器是一样的。现在的程序和刚才的相比只是少了一个User-Agent结果就截然不同,有时候会出现加上了User-Agent但是还是不能得到数据,这时候就再加一些其他的东西,比如“Referer”、“Origin”、“Content-Type”这些字段。尽量的让自己的爬虫像一个浏览器,后期可能还要像一个人一样。

猜你喜欢

转载自blog.csdn.net/williamgavin/article/details/81348914