zoukankan      html  css  js  c++  java
  • 爬虫一(requests模块)

    1、释义

    网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。另外一些不常使用的名字还有蚂蚁、自动索引、模拟程序或者蠕虫。

    2、申明

    爬虫也是只能爬取公开网站,公开的额数据,别人加密的,涉及到隐私的,不能随便搞,否则,后果自负

    3、安装模块

    pip install requests

    4、http定义的与服务器交互的几种方法

    • get         仅仅获取资源的信息,不增加或者修改数据。
    • post      一般丢该服务器上的资源,一般我们通过form表单进行提交请求
    • put         增加
    • delete    删除
    import requests
    requests.get("http://www.baidu.com")
    requests.post("http://www.jd.com")
    requests.put("http://www.jd.com")
    requests.delete("http://www.jd.com")

    5、传递参数

    get方式:

    params = {'key1': 'hello', 'key2': 'world'}
    url = 'https://www.jd.com'
    r = requests.get(url=url, params=params)
    print(r.url)
    结果:
    https://www.jd.com/?key1=hello&key2=world

    我们也可以直接
    requests.get('https://www.jd.com/?key1=hello&key2=world')

    post方式:

    params = {'key1': 'hello', 'key2': 'world'}
    r = requests.post("http://httpbin.org/post", data=params)
    print(r.text)
    http://httpbin.org/post 是requests提供的官网地址,通过json的方式给大家返回。可以看到我们返回的数据。Post的数据参数是data,都是字典的类型,但是urllib就没法接受字典类型,必须是字符串
    结果:
    {
    "args": {},
    "data": "",
    "files": {},
    "form": {
    "key1": "hello",
    "key2": "world"
    },
    "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "close",
    "Content-Length": "21",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.18.4"
    },
    "json": null,
    "origin": "1.202.119.5",
    "url": "http://httpbin.org/post"
    }

    6、响应http的请求

    url = 'https://www.qiushibaike.com/'
    r = requests.get(url=url)
    print(r.text)
    print(r.encoding) #查看编码

    print(type(r.text)) <class 'str'>
    print(type(r.content)) <class 'bytes'>

    7、Requests中text和content的区别

    • r.text     返回的是str类型的数据
    • r.content  返回的是bytes型也就是二进制的数据

    也就是说,如果你想取文本,可以通过r.text,如果想取图片或文件,则可以通过r.content

    下载图片一:

    url = 'http://show.huitu.com/pic/20180330/r36717.jpg'
    session = requests.session()
    picture = session.get(url)
    with codecs.open("pic.jpg", 'wb') as fd:
    for i in picture.iter_content():
    fd.write(i)

    下载图片二:

    url = 'http://show.huitu.com/pic/20180330/r36717.jpg'
    session = requests.session()
    response = session.get(url)
    img = response.content
    with codecs.open('p.jpg', 'wb') as file:
    file.write(img)

    8、Request的其他常用方法

    header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36'}
    r = requests.get('https://www.qiushibaike.com/', headers=header)
    print(r.text) #文本
    print(r.request) #<PreparedRequest [GET]>
    print(r.headers)
    #{'Server': 'nginx', 'Date': 'Sun, 14 Jan 2018 12:37:48 GMT', 'Content-Type': 'text/html; charset=UTF-8', 'Content-Length': '17011', 'Connection': 'keep-alive', 'Content-Encoding': 'gzip', 'Set-Cookie': '_xsrf=2|5f47375e|e7eb37220e28518c03d1ea75a2c374e7|1515936871; Path=/', 'Vary': 'User-Agent, Accept-Encoding', 'Etag': '"d0c332a18dc290c35570931f9d699ef756db2450"'}
    print(r.cookies) #cookies的信息
    print(r.cookies[‘_xsrf’]) #可以通过字典的方式取值
    print(r.url) #请求的url是多少
    print(r.status_code) #http的状态返回码

    9、Request更改请求头信息

    header = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36'}
    r = requests.get('https://www.qiushibaike.com/', headers=header)
    print(r.text)
    print(r.headers)

    可以通过定义一个list,然后通过random模块随机取一个header信息进行访问,防止反爬虫的操作

    10、Request的会话对象

    s = requests.session()

    S = requests.Session() # python2

    所有一次会话的信息都保存在s中,只需要对s进行操作就可以了,如:

    s.get(url)

    11、Requests通过会话信息来获取cookie信息

    Cookie的五要素:Name   value   domain   path  expires

    import requests

    def save_cookie():
    s = requests.session()
    s.get('https://www.hao123.com/')
    print(s.cookies)
    print(s.cookies.keys())
    print(s.cookies.values())
    for i in s.cookies:
    print(i)
    print(i.name, i.value, i.domain, i.path, i.expires)

    if __name__ == '__main__':
    save_cookie()

    12、Cookie的常用属性

    Cookie常用的一些属性:

    • Domain  域
    • Path       路径
    • Expires  过期时间
    • name    对应的key值
    • value        key对应的value值

    cookie中的domain代表的是cookie所在的域,默认情况下就是请求的域名,例如请求http://www.server1.com/files/hello, 那么响应中的set-Cookie默认会使用www.server1.com作为cookie的domain,在浏览器中也是按照domain来组织cookie的。 我们可以在响应中设置cookie的domain为其他域,但是浏览器并不会去保存这些domain为其他域的cookie。

    cookie中的path能够进一步的控制cookie的访问,当path=/; 当前域的所有请求都可以访问到这个cookie。 如果path设为其他值,比如path=/test,那么只有/test下面的请求可以访问到这个cookie。

    使用已知cookie信息,如何访问网站:

    import requests

    url = 'http://httpbin.org/cookies'
    r = requests.get(url, cookies={'key1': 'value1', 'key2': 'value2'})
    print(r.text)

    #结果:
    {
    "cookies": {
    "key1": "value1",
    "key2": "value2"
    }
    }

    13、代理访问

    采集时为避免被封IP,经常会使用代理。

    requests也有相应的proxies属性:

    import requests
    proxies = {
    "http": "http://182.108.5.246:8118",
    # "https": "http://112.117.184.219:9999",
    }
    r1 = requests.get("http://2017.ip138.com/ic.asp", proxies=proxies)
    r2 = requests.get("http://2017.ip138.com/ic.asp")
    print(r1.text)
    print(r2.text)
    [182.108.5.246]
    [106.38.115.34]

    # 如果代理需要账户和密码,则需这样:
    proxies = {
    "http": "http://user:pass@10.10.1.10:3128/",
    }

    14、requests的中文乱码问题

    import requests

    param = {"key1": "hello", "key2": "world"}
    url = 'https://www.baidu.com/'
    r = requests.get(url=url)
    print(r.encoding) #ISO-8859-1默认使用的是这个
    r.encoding = "utf-8"
    print(r.text)

    #这样就可以正常显示了

    15、总结

    Requests给你提供的所有接口,在传输数据的时候,都可以以key:value的形式进行传输,这个也是我为什么特别喜欢使用requests的原因,如果使用urllib,那么就没有这么幸运了,很多事情都需要自己去处理,并不可以直接通过dict的形式进行传输,需要进行装换

  • 相关阅读:
    进程通信
    python模块成像库pillow
    python模块IO
    python模块StringIO和BytesIO
    DJango重写用户模型
    DJango模型Meta选项详解
    DJango中事务的使用
    批量删除文件
    批量修改文件名字或后缀
    自定义中间件实现插拔设计
  • 原文地址:https://www.cnblogs.com/Jweiqing/p/9179480.html
Copyright © 2011-2022 走看看