python网络爬虫学习日记-----urllib中urlopen()的使用

urllib的四个模块

  • request:基本的Http请求模块
  • error:异常模块
  • parse:工具模块,url处理方法
  • robotparser:识别网上的robots.tst文件,判断网站是否可爬

发送请求

  • urlopen()
    先使用urlopen()进行最基本的页面抓取
    import urllib.request
    response=urllib.request.urlopen(‘https://www.python.org’)
    print(response.read().decode(‘utf-8’))
    python网络爬虫学习日记-----urllib中urlopen()的使用_第1张图片
    这样就获得了python官网的html代码
    再用type(response)返回response的类型
    返回结果:
    可以看到返回了一个HTTPResponse类型的对象 其中包含了read(),readinto(),gethender(“””)获取响应头信息中的子信息,getheaders()响应头信息,fileno()等方法及msg,version,status获取响应状态码,reason,debuglevel,closed各种属性
    urlopen()还有几个参数
    1).data参数为可选参数,需要bytes()方法转化,并且请求方式变成post
#urlopen()中data参数练习
data=bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8')
response=urllib.request.urlopen('http://httpbin.org/post',data=data)
print(response.read())

这样我们传递的参数会出现在form字段中 模拟了表单提交方式,以post方式传输数据

2)timeout参数

#urlopen()中timeout参数说明  超过请求指定时间报异常
try:
    response=urllib.request.urlopen('http://httpbin.org/get',timeout=0.1)
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout):
        print("time out")

运行结果:
在这里插入图片描述

下一个笔记介绍 比urlopen()更强大的request()

你可能感兴趣的:(urllib)