zoukankan      html  css  js  c++  java
  • 爬虫

     requests模块是Python中发送网络请求的一款非常简洁、高效的模块。

    pip install requests
     
    import requests
    requests.get("https://www.python.org/")
    requests.post("https://www.python.org/")
    requests.put("https://www.python.org/")
    requests.patch("https://www.python.org/")
    requests.delete("https://www.python.org/")
    requests.head("https://www.python.org/")
    requests.options("https://www.python.org/")
    # 指定请求方式 requests.request("get","https://www.python.org/")
     
    当请求发送成功后,会返回一个response对象。 
     
    2.2 get请求
     
    参数描述
    params 字典,get请求的参数,value支持字符串、字典、字节(ASCII编码内)
    headers 字典,本次请求携带的请求头
    cookies 字典,本次请求携带的cookies

     演示如下:

    import requests
    res = requests.get( url="http://127.0.0.1:5000/index", params={"key": "value"}, cookies={"key": "value"}, )
    print(res.content)
     
    2.3 post 请求
     

      基本的post请求参数如下:

    参数描述
    data 字典,post请求的参数,value支持文件对象、字符串、字典、字节(ASCII编码内)
    headers 字典,本次请求携带的请求头
    cookies 字典,本次请求携带的cookies

       演示如下:

    import requests
    res = requests.post( url="http://127.0.0.1:5000/index", # 依旧可以携带 params data={"key": "value"}, cookies={"key": "value"}, )
    print(res.content)
     
    2.4 高级参数

      更多参数:

    参数描述
    json 字典,传入json数据,将自动进行序列化,支持get/post,请求体传递
    files 字典,传入文件对象,支持post
    auth 认证,传入HTTPDigestAuth对象,一般场景是路由器弹出的两个输入框,爬虫获取不到,将用户名和密码输入后会base64加密然后放入请求头中进行交给服务端,base64("名字:密码"),请求头名字:authorization
    timeout 超时时间,传入float/int/tuple类型。如果传入的是tuple,则是 (链接超时、返回超时)
    allow_redirects 是否允许重定向,传入bool值
    proxies 开启代理,传入一个字典
    stream 是否返回文件流,传入bool值
    cert 证书地址,这玩意儿来自于HTTPS请求,需要传入该网站的认证证书地址,通常来讲如果是大公司的网站不会要求这玩意儿
     
    2.4 session 对象

     如果爬取一个网站,该网站可能会返回给你一些cookies,对这个网站后续的请求每次都要带上这些cookies比较麻烦。

       所以可以直接使用session对象(自动保存cookies)发送请求,它会携带当前对象中所有的cookies

    def requests_session():
      import requests
      # 使用session时,会携带该网站中所返回的所有cookies发送下一次请求。
      # 生成session对象
      session = requests.Session()
      ### 1、首先登陆任何页面,获取
      cookie i1 = session.get(url="http://dig.chouti.com/help/service")
      ### 2、用户登陆,携带上一次的cookie,后台对cookie中的 gpsd 进行授权
      i2 = session.post( url="http://dig.chouti.com/login", data={ 'phone': "8615131255089", 'password': "xxxxxx", 'oneMonth': "" } )
      i3 = session.post( url="http://dig.chouti.com/link/vote?linksId=8589623", )
     
      print(i3.text)
     
    2.6  response 对象

     以下是response对象的所有参数:

    response.request.headers      响应对应的请求头

    参数描述
    response.text 返回文本响应内容
    response.content 返回二进制响应内容
    response.json 如果返回内容是json格式,则进行序列化
    response.encoding 返回响应内容的编码格式
    response.status_code 状态码
    response.headers 返回头/响应头
    response.cookies 返回的cookies对象
    response.cookies.get_dict() 以字典形式展示返回的cookies对象
    response.cookies.items() 以元组形式展示返回的cookies对象
    response.url 返回的url地址
    response.history 这是一个列表,如果请求被重定向,则将上一次被重定向的response对象添加到该列表中

    编码问题

       并非所有网页都是utf8编码,有的网页是gbk编码。

       此时如果使用txt查看响应内容就要指定编码格式:

    import requests
    response=requests.get('http://www.autohome.com/news')
    response.encoding='gbk'
    print(response.text)
     

     下载文件

       使用response.context时,会将所有内容存放至内存中。

       如果访问的资源是一个大文件,而需要对其进行下载时,可使用如下方式生成迭代器下载:

    import requests
    response=requests.get('http://bangimg1.dahe.cn/forum/201612/10/200447p36yk96im76vatyk.jpg')
    with open("res.png","wb") as f:
      for line in response.iter_content():
        f.write(line)
     

       json返回内容

       如果确定返回内容是json数据,则可以通过response.json进行查看:

    import requests
    response = requests.get("http://127.0.0.1:5000/index")
    print(response.json())
     
    4.0 xpath
     
    pip3 install lxml

     加载文档:

    from lxml import etree
     
    # 解析网络爬取的html源代码
    root = etree.HTML(response.text,etree.HTMLParser())    # 加载整个HTML文档,并且返回根节点<html>
     
     
    # 解析本地的html文件
    root = etree.parse(fileName,etree.HTMLParser())
     
    4.1  基本选取符号
     
    符号描述
    / 从根节点开始选取
    // 不考虑层级关系的选取节点
    . 选取当前节点
    .. 选取当前节点的父节点
    @ 属性检测
    [num] 选取第n个标签元素,从1开始
    /@attrName 选取当前元素的某一属性
    * 通配符
    /text() 选取当前节点下的直系文本内容
    //text() 选取当前文本下的所有文本内容
    | 返回符号两侧所匹配的全部标签

    注意:xPath选择完成后,返回的始终是一个list,与jQuery类似,可以通过Index取出Element对象

    from lxml import etree

    root = etree.parse("./testDataDocument.html",etree.HTMLParser())

    # 从根节点开始找 /

    form_list = root.xpath("/html/body/form")

    print(form_list) # [<Element form at 0x203bd29c188>]

    # 不考虑层级关系的选择节点 //

    input_list = root.xpath("//input")

    print(input_list)

    # 从当前的节点开始选择 即第一个form表单 ./

    select_list = form_list[0].xpath("./fieldset/select")

    print(select_list)

    # 选择当前节点的父节点 ..

    form_parent_list = form_list[0].xpath("..")

    print(form_parent_list) # [<Element body at 0x1c946e4c548>]

    # 属性检测

    @ 选取具有name属性的input框

    input_username_list = root.xpath("//input[@name='username']")

    print(input_username_list) # 属性选取

    @ 获取元素的属性 attrs_list = root.xpath("//p/@title")

    print(attrs_list)

    # 选取第n个元素,从1开始

    p_text_list = root.xpath("//p[2]/text()")

    print(p_text_list)

    # 通配符 * 选取所有带有属性的标签

    have_attrs_ele_list = root.xpath("//*[@*]")

    print(have_attrs_ele_list)

    # 获取文本内容-直系

    print(root.xpath("//form/text()"))

    # 结果:一堆

    # 获取文本内容-非直系

    print(root.xpath("//form//text()"))

    # 结果:本身和后代的text

    # 返回所有input与p标签

    ele_list = root.xpath("//input|//p")

    print(ele_list)

  • 相关阅读:
    新一篇: 正则表达式使用详解
    C#預處理指令
    [转]SQL Server 2005 Beta 2 TransactSQL 增强功能
    SQL Server 2005之PIVOT/UNPIVOT行列转换
    爬虫入门到放弃系列01:什么是爬虫
    我的程序员之路01:自学Java篇
    Java入门者:如何写出美观的Java代码?
    JedisCluster使用pipeline操作Redis Cluster最详细从0到1实现过程
    IDEA超神之路:安装、运行HelloWorld以及激活到2099年的第一场雪
    软考系统架构师、信息系统项目管理师、系统分析师、系统规划与管理师和网络规划师资料大汇总
  • 原文地址:https://www.cnblogs.com/plyc/p/14499134.html
Copyright © 2011-2022 走看看