Urllib库基本使用

什么是Urllib


Urllib是Python3内置的HTTP请求库

常用模块 释义
urllib.request 请求模块
urllib.error 异常处理模块
urllib.parse url解析模块
urllib.robotparser robots.txt解析模块

测试网站http://httpbin.org

例1:发送最基本的get请求,获取html代码---request.urlopen()

from urllib import request
response = request.urlopen('http://www.baidu.com')#发送请求,获取响应内容
result = response.read()#提取响应的字节流
print(result.decode('utf-8'))#将字节流转换为'utf-8',并打印

例2:post请求数据data(需要bytes类型)---parse.urlencode()

from urllib import request,parse
data = bytes(parse.urlencode({'word':'hi'}),encoding='utf-8')
response = request.urlopen('http://httpbin.org/post',data=data)
print(response.read())

例3:创造请求头,增加headers---request.Request()

from urllib import request,parse
url = 'http://httpbin.org/post'
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36",
          }
dict = {
    'name':'Hello',
}
data = bytes(parse.urlencode(dict),encoding='utf-8')
req = request.Request(url=url,data=data,headers=headers,method='POST')
response = request.urlopen(req)
print(response.read().decode('utf-8'))
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1 前言 作为一名合格的数据分析师,其完整的技术知识体系必须贯穿数据获取、数据存储、数据提取、数据分析、数据挖掘、...
    whenif阅读 18,179评论 45 523
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,374评论 19 139
  • 前言: 什么是cookie? Cookie,指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端...
    小喜_ww阅读 6,416评论 0 7
  • 本文是爬虫系列文章的第一篇,主要讲解 Python 3 中的 urllib 库的用法。urllib 是 Pytho...
    猴哥爱读书阅读 35,295评论 8 42
  • 想着我们曾经也在一起嬉笑打闹,看着渐远的心,面对着生硬的对话,发现一切都只是曾经了,所以劝诫自己!就像每向前走一...
    木子_9765阅读 1,826评论 0 0