python3 urllib及requests基本使用

在python中,urllib是请求url链接的标准库,在python2中,分别有urllib和urllib,在python3中,整合成了一个,称谓urllibhtml

一、urllib.requestpython

  request主要负责构建和发起网络请求git

  1)GET请求(不带参数)github

    response = urllib.request.urlopen(url,data=None, [timeout, ]*)json

    返回的response是一个http.client.HTTPResponse objectapi

    response操做:浏览器

      a) response.info() 能够查看响应对象的头信息,返回的是http.client.HTTPMessage object服务器

      b) getheaders() 也能够返回一个list列表头信息cookie

      c) response能够经过read(), readline(), readlines()读取,可是得到的数据是二进制的因此还须要decode将其转化为字符串格式。网络

      d) getCode() 查看请求状态码

      e) geturl() 得到请求的url

    

    >>>>>>>

    

  2)GET请求(带参数)

    须要用到urllib下面的parse模块的urlencode方法

    param = {"param1":"hello", "param2":"world"}

    param = urllib.parse.urlencode(param)    # 获得的结果为:param2=world&param1=hello

    url = "?".join([url, param])  http://httpbin.org/ip?param1=hello&param2=world

    response = urllib.request.urlopen(url)

 

  3)POST请求:

    urllib.request.urlopen()默认是get请求,可是当data参数不为空时,则会发起post请求

    传递的data须要是bytes格式

    设置timeout参数,若是请求超出咱们设置的timeout时间,会跑出timeout error 异常。

    param = {"param1":"hello", "param2":"world"}

    param = urllib.parse.urlencode(param).encode("utf8") # 参数必需要是bytes

    response = urllib.request.urlopen(url, data=param, timeout=10)

  4)添加headers

    经过urllib发起的请求,会有一个默认的header:Python-urllib/version,指明请求是由urllib发出的,因此遇到一些验证user-agent的网站时,咱们须要伪造咱们的headers

    伪造headers,须要用到urllib.request.Request对象

    

    headers = {"user-agent:"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"}

    req = urllib.request.Request(url, headers=headers)

    resp = urllib.request.urlopen(req)

    

    

    对于爬虫来讲,若是一直使用同一个ip同一个user-agent去爬一个网站的话,可能会被禁用,因此咱们还能够用用户代理池,循环使用不一样的user-agent

    原理:将各个浏览器的user-agent作成一个列表,而后每次爬取的时候,随机选择一个代理去访问

    uapool = ["谷歌代理", 'IE代理', '火狐代理',...]

    curua = random.choice(uapool)

    headers = {"user-agent": curua}

    req = urllib.request.Request(url, headers=headers)

    resp = urllib.request.urlopen(req)

  5)添加cookie

    为了在请求的时候,带上cookie信息,须要构造一个opener

    须要用到http下面的cookiejar模块

    from http import cookiejar

    from urllib import request

    a) 建立一个cookiejar对象

      cookie = cookiejar.CookieJar()

    b) 使用HTTPCookieProcessor建立cookie处理器

      cookies = request.HTTPCookieProcessor(cookie)

    c) 以cookies处理器为参数建立opener对象

      opener = request.build_opener(cookies)

    d) 使用这个opener来发起请求

      resp = opener.open(url)

    e) 使用opener还能够将其设置成全局的,则再使用urllib.request.urlopen发起的请求,都会带上这个cookie

      request.build_opener(opener)

      request.urlopen(url)

  6)IP代理

    使用爬虫来爬取数据的时候,经常须要隐藏咱们真实的ip地址,这时候须要使用代理来完成

    IP代理可使用西刺(免费的,可是不少无效),大象代理(收费)等

    代理池的构建能够写固定ip地址,也可使用url接口获取ip地址

    固定ip:

      from urllib import request

      import random

      ippools = ["36.80.114.127:8080","122.114.122.212:9999","186.226.178.32:53281"]

      def ip(ippools):

        cur_ip = random.choice(ippools)

        # 建立代理处理程序对象

        proxy = request.ProxyHandler({"http":cur_ip})

        # 构建代理

        opener = request.build_opener(proxy, request.HttpHandler)

        # 全局安装

        request.install_opener(opener)

      for i in range(5):

        try:

          ip(ippools)

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

          resp = request.urlopen(cur_url).read().decode("utf8")

        excep Exception as e:

          print(e)

    使用接口构建IP代理池(这里是以大象代理为例)

      def api():

        all=urllib.request.urlopen("http://tvp.daxiangdaili.com/ip/?tid=订单号&num=获取数量&foreign=only")

        ippools = []

        for item in all:

          ippools.append(item.decode("utf8"))

        return ippools

      其余的和上面使用方式相似

  7)爬取数据并保存到本地 urllib.request.urlretrieve()

    如咱们常常会须要爬取一些文件或者图片或者音频等,保存到本地

    urllib.request.urlretrieve(url, filename)

  8)urllib的parse模块

    前面第2)中,咱们用到了urllib.parse.urlencode()来编码咱们的url

    a)urllib.parse.quote()

      这个多用于特殊字符的编码,如咱们url中须要按关键字进行查询,传递keyword='诗经'

      url是只能包含ASCII字符的,特殊字符及中文等都须要先编码在请求

      

      要解码的话,使用unquote

      

    b)urllib.parse.urlencode()

      这个一般用于多个参数时,帮咱们将参数拼接起来并编译,向上面咱们使用的同样

      

  9)urllib.error

    urllib中主要两个异常,HTTPError,URLError,HTTPError是URLError的子类

    HTTPError包括三个属性:

      code:请求状态码

      reason:错误缘由

      headers:请求报头

    

 

二、requests

  requests模块在python内置模块上进行了高度的封装,从而使得python在进行网络请求时,变得更加人性化,使用requests能够垂手可得的完成浏览器可有的任何操做。

  1)get:

    requests.get(url)  #不带参数的get请求

    requests.get(url, params={"param1":"hello"})  # 带参数的get请求,requests会自动将参数添加到url后面

  2)post:

    requests.post(url, data=json.dumps({"key":"value"}))

  3)定制头和cookie信息

    header = {"content-type":"application/json","user-agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"}

    cookie = {"cookie":"cookieinfo"}

    requests.post(url, headers=header, cookie=cookie)

    requests.get(url, headers=header, cookie=cookie)

  4)返回对象操做:

    使用requests.get/post后会返回一个response对象,其存储了服务器的响应内容,咱们能够经过下面方法读取响应内容

    resp = requests.get(url)

    resp.url           # 获取请求url

    resp.encoding           # 获取当前编码

    resp.encoding='utf8'      # 设置编码

    resp.text              # 以encoding解析返回内容。字符串形式的响应体会自动根据响应头部的编码方式进行解码

    resp.content          # 以字节形式(二进制)返回。字节方式的响应体,会自动解析gzip和deflate压缩

    resp.json()          # requests中内置的json解码器。以json形式返回,前提是返回的内容确实是json格式的,不然会报错

    resp.headers         # 以字典形式存储服务器响应头。可是这个字典不区分大小写,若key不存在,则返回None

    resp.request.headers   # 返回发送到服务器的头信息

    resp.status_code       # 响应状态码

    resp.raise_for_status()    # 失败请求抛出异常

    resp.cookies       # 返回响应中包含的cookie

    resp.history         # 返回重定向信息。咱们能够在请求时加上allow_redirects=False 来阻止重定向

    resp.elapsed       # 返回timedelta,响应所用的时间 

    具体的有哪些方法或属性,能够经过dir(resp)去查看。

  5)Session()

    会话对象,可以跨请求保持某些参数。最方便的是在同一个session发出的全部请求之间保持cookies

    s = requests.Session()

    header={"user-agent":""}

    s.headers.update(header)

    s.auth = {"auth", "password"}

    resp = s.get(url)

    resp1 = s.port(url)

 

  6)代理

    proxies = {"http":"ip1", "https":"ip2"}

    requests.get(url, proxies=proxies)

  7)上传文件

    requests.post(url, files={"file": open(file, 'rb')})

    把字符串当作文件上传方式:

    requests.post(url, files={"file":('test.txt', b'hello world')}})  # 显示的指明文件名为test.txt

  8)身份认证(HTTPBasicAuth)

    from requests.auth import HTTPBasicAuth

    resp = request.get(url, auth=HTTPBasicAuth("user", "password"))

    另外一种很是流行的HTTP身份认证形式是摘要式身份认证

    requests.get(url, HTTPDigestAuth("user", "password"))

  9)模拟登录GitHub demo

    from bs4 import BeautifulSoup

    # 访问登录界面,获取登录须要的authenticity_token

    url = "https://github.com/login"

    resp = requests.get(url)

    # 使用BeautifulSoup解析爬取的html代码并获取authenticity_token的值

    

    s = BeautifulSoup(resp.text, "html.parser")

    token = s.find("input", attrs={"name":"authenticity_token"}).get("value")

    # 获取登录须要携带的cookie

    cookie = resp.cookies.get_dict()

    # 带参数登录

    login_url = "https://github.com/session"

    

    login_data = {

      "commit":"Sign+in",

      "utf8":"✓",

      "authenticity_token":token,

      "login":username,

       "password":password

    }

    resp2 = requests.post(login_url, data=login_data, cookies=cookie)

    # 获取登录后的cookie

    logged_cookie = resp2.cookies.get_dict()

    # 携带cookie就能够访问你想要访问的任意网页了

    requests.get(url, cookies=logged_cookie)

    # 也能够把爬取的网页写入本地文件

    with open(file, "w", encoding='utf8') as f:

      f.write(resp2.text)

 

 

参考:https://www.cnblogs.com/ranxf/p/7808537.html

相关文章
相关标签/搜索