爬虫(第一部分)

requests 模块

ps:知识点前提

爬虫备知识:http协议:https://www.cnblogs.com/pyedu/p/10287967.html

    post请求才有请求体,post请求数据放在请求体中,get请求是将请求数据放在url的”?“后面,类似于 https://www.baidu.com/s?a=12&b=133
?之后才是请求数据

一:robots.txt协议

  如果自己的门户网站中的指定页面中的数据不想让爬虫程序爬取到的话,那么则可以通过编写一个robots.txt的协议文件来约束爬虫
    程序的数据爬取。robots协议的编写格式可以观察淘宝网的robots(访问www.taobao.com/robots.txt即可)。但是需要注意的
    是,该协议只是相当于口头的协议,并没有使用相关技术进行强制管制,所以该协议是防君子不防小人。但是我们在学习爬虫阶段编写的
    爬虫程序可以先忽略robots协议。

 二:requests模块

01:requests模块简介:
    Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库,Requests它会比urllib更加方便,
    可以节约我们大量的工作。一句话,requests是python实现的最简单易用的HTTP库,建议爬虫使用requests库。默认安装好python之后,是没有安装requests
    模块的,需要单独通过pip安装

02:安装requests模块
    pip安装:pip install requests (python版本不同,有的用的时pip3 install requests 安装)

 三:requests的基本语法( ps: ---#res.content 写入文件的是bytes字节流格式

  01:requests模块支持的请求方式:

import requests
requests.get("http://httpbin.org/get")
requests.post("http://httpbin.org/post")
requests.put("http://httpbin.org/put")
requests.delete("http://httpbin.org/delete")
requests.head("http://httpbin.org/get")
requests.options("http://httpbin.org/get")

   02:get请求:

    001:基本请求案例:
import requests  #倒入模块
res=requests.get("https://www.bilibili.com/",)

with open("bibi.html","wb") as f: #写入文件,wb  pycharm默认的是encoding=“utf8”
    f.write(res.content)     #res.content   写入文件的是bytes字节流格式

    002:带参数的get请求

#含参数:(有些网站没有反扒机制,因此可以不用写header 模拟人为操作)
import requests
url="https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu&wd=熊猫"
res=requests.get(url=url,headers={"User-Agent": "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) 
                                                Chrome/72.0.3626.119 Safari/537.36"}) with open("panda.html","wb") as f: f.write(res.content) ps:因为网站有反爬机制,通过读取脚本的请求头格式,发现脚本程序没有User-Agent(这次请求是机器在请求),不允许爬取网页,所以我们需要模拟 是手动操作,因此需要在请求头中添加headers。

      003:含cookies请求:

(有些网站需要登陆验证后才能访问下一网页,则会个实际上是网站在你访问本页面的时候给你请求头 加上cookies钥匙,
在你访问,你需要带上这个cookies钥匙才能去访问下一个网页)
例子:
uuid 产生随机字符串
eg:sbid=str(uuid.uuid4)  #产生随机字符串
语法:import uuid
    uuid.uuid1()
    UUID('847d3162-3b2f-11e9-9fe2-a0481cc00100')

------------------------------

import uuid
import requests
url="https://www.panda.tv/all?pdt=1.18.pheader-n.1.6jp4lv9639d"
cookies=dict(sbid=str(uuid.uuid4()))
res=requests.get(url,cookies=cookies)
with open("pandatv.html","wb",) as f:

    f.write(res.content)

     004:含有session请求:

# res=requests.post("/login/")
# dic={}
# requests.get("/index/",cookies=dic)
# ########
# session=requests.session()
# session.post("/login/")
# session.get("/index/")  #session对象会将上一次给的cookies 带入这次的请求信息中,发送给服务端

   03:post请求

--ps:没有指定请求头,#默认的请求头:application/x-www-form-urlencoed,也可以指定是json 这样请求头的格式就json,
发送的就是bytes类型数据
import requests
res1 = requests.post(url="http://httpbin.org/post?a=11", data={"name": "tom"})
print(res1)  # <Response [200]>  状态码
print(res1.text)  # 相应体中德基本内容,其他省略  {"args": {"a": "11"},"form": {"name": "tom"}, },

print("------------------------------------------------")

res2 = requests.post(url="http://httpbin.org/post", data={"name": "xmk"})
print(res2)  ##<Response [200]>  状态码
print(res2.text)  # 相应体中德基本内容,其他省略  {"args": {},"form": {"name": "tom"}, },

 四:response基本语法与例子

   01:例子:

import requests
res=requests.get("https://www.autohome.com.cn/beijing/")
print("1>>",res.content) #获取的时bytes类型,在pycharm中自动转换成utf8格式
print("----------------------------")
print("2>>",res.encoding) #获取编码格式 gb2312
print("3>>",res.text)  #获取文本格式内容
res.encoding="gbk"

with open("qc.html","w") as f:  #w是文本写入文件,wb是字节写入,所以这里用wb是不行的
    f.write(res.text)

   02:01例子另外的爬取方法,写入字节,平台会自动转成相应的格式

import requests
res=requests.get("https://www.autohome.com.cn/beijing/")
print("1>>",res.content) #获取的时bytes类型,在pycharm中自动转换成utf8格式
print("----------------------------")
print("2>>",res.encoding) #获取编码格式 gb2312
print("3>>",res.text)  #获取文本格式内容

with open("qi2.html","wb") as f:
    f.write(res.content)

 五:爬取图片,视频,音频(它们三者本质上就是一串二进制bytes代码,读写的时候用wb就可以的)

  01:爬取图片

import requests
res=requests.get("http://attachments.gfan.net.cn/forum/201412/29/175429ldkpipr11pldt10d.jpg.thumb.jpg")
with open("xhr.jpg","wb") as f:
    f.write(res.content)

   02:爬取视频:(部分网站的原视频的url可以在网页详情页中找到)

url="https://video.pearvideo.com/mp4/third/20190227/cont-1522961-10477784-165810-hd.mp4"
import requests
res = requests.get(url)
with open("小视频.mp4", "wb") as f:
    f.write(res.content)

   03:02例子有一个缺点就是视频写入的时候会对硬盘存储造成影响,因为wb是一下子全部写入硬盘的,而逐行写入会规避这个缺点

import requests
res = requests.get("http://y.syasn.com/p/p95.mp4")
with open("小视频02.mp4", "wb") as f:
for line in res.iter_content():
    f.write(line)

 六:响应json数据

  01:对获取的数据只是一个str字符串,并不利于利用,因此将数据转换成json字典形式更加容易分析

import requests,json
res=requests.get("http://httpbin.org/get")
print(res.text)
print("_--------------")
# print(type(res.text))   #<class 'str'>

#方法01:比较麻烦
print("json>>",json.loads(res.text))

#方法二:直接获取json数据
print("直接获取json数据〉〉〉",res.json())
print("json数据格式〉〉〉",type(res.json())) #<class 'dict'>

七:重定向和历史

  01:重定向:例如:在地址栏只输入:http://www.jd.com,但是浏览器会会自动跳转到https://www.jd.com/ 下,类似这样就是重定向

import requests
res=requests.get("http://www.jd.com")
print(res.history)  #[<Response [302]>]  中间跳转过的状态码
print(">>",res.text) #拿到的是已经跳转成功后的页面
print(res.status_code)  #200  代表ok

  02:allow_redirects=True 不写的话默认是True 允许重定向

import requests
res1=requests.get("http://www.taobao.com",allow_redirects=False)
print(res1.history) #[] #跳转的那个状态页码,不允许重定向,那就是http://www.taobao.com 页面。默认的时允许重定向
print(res1.status_code) #302

八:IP代理:(待更新。。。。)

一些网站会有相应的反爬虫措施,例如很多网站会检测某一段时间某个IP的访问次数,如果访问频率太快以至于看起来不像正常访客,它可能就会会禁止这个IP的访问。所以我们需要设置
一些代理服务器,每隔一段时间换一个代理,就算IP被禁止,依然可以换个IP继续爬取。 res
=requests.get('http://httpbin.org/ip', proxies={'http':'110.83.40.27:9999'}).json() print(res)

 

原文地址:https://www.cnblogs.com/one-tom/p/10451690.html