urllib 模块的用法

urllib的用法

介绍

  • urllib 是 python3.X中提供的一系列操作URL的库,它可以轻松的模拟用户使用浏览器访问网页

使用步骤

  1. 导入 urllib 库的 request 模块

        from urllib import request
    
  2. 请求 url

        res = request.urlopen('www.baidu.com')
    

    res的返回值是一个http对象

  3. 使用相应对象输出数据

        print(res.read().decode('utf-8'))
    

    此处的decode编码格式视html代码的而定

  4. 模拟一个真实的浏览器请求

    1. 携带 User-Agent 请求头信息
      • 方法1:
            req = request.Request(url)
            req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36')
            res = request.urlopen(req)
            print(res.read().decode('utf8'))
        
      • 方法2:
            header = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36'
            }
            req = request.Requset(url=url, headers=header)
            res = request.urlopen(req)
            print(res.read().decode('utf8'))
        
    2. 发送POST请求
      1. 导入 urllib 库下面的parse
            from urllib import parse
        
      2. 使用 urlencode 生成 post 数据
            post_data = {
                'key1': value1,
                'key2': value2,
                'key3': value3
            }
            post_data = parse.urlencode(post_data)
        
      3. 使用生成的数据发送 post 请求,注意数据要转码为 'utf8' 格式
            res = request.urlopen(url, data=post_data.encode('utf-8'))
        
      4. 使用 read() 查看响应信息
            print(res.read().decode('utf8'))
        

你可能感兴趣的:(urllib 模块的用法)