分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 软件开发

urllib

发布时间:2023-09-06 02:33责任编辑:赖小花关键词:url

什么是urllib

Urllib是python内置的HTTP请求库
包括以下模块
urllib.request 请求模块
urllib.error 异常处理模块
urllib.parse url解析模块
urllib.robotparser robots.txt解析模块

urlopen

关于urllib.request.urlopen参数的介绍:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

import urllib.requestresponse = urllib.request.urlopen(‘http://www.baidu.com‘)print(response.read().decode(‘utf-8‘))

 urlopen一般常用的有三个参数,它的参数如下:
urllib.requeset.urlopen(url,data,timeout)
response.read()可以获取到网页的内容,如果没有read(),将返回如下内容

data参数的使用

上述的例子是通过请求百度的get请求获得百度,下面使用urllib的post请求

import urllib.parseimport urllib.requestdata=bytes(urllib.parse.urlencode({‘word‘:‘hello‘}),encoding=‘utf8‘)print(data)response=urllib.request.urlopen(‘http://httpbin.org/post‘,data=data)html=response.read()print(html)

  这里就用到urllib.parse,通过bytes(urllib.parse.urlencode())可以将post数据进行转换放到urllib.request.urlopen的data参数中。这样就完成了一次post请求。
所以如果我们添加data参数的时候就是以post请求方式请求,如果没有data参数就是get请求方式

  关于get和post:在客户机和服务机之间进行请求-响应时,两种最常被用到的方法是:get和post。

    get  从指定资源请求数据

    post  向指定的资源提交要被处理的数据

      

timeout参数的使用

在某些网络情况不好或者服务器端异常的情况会出现请求慢的情况,或者请求异常,所以这个时候我们需要给
请求设置一个超时时间,而不是让程序一直在等待结果。例子如下:

import urllib.requestresponse = urllib.request.urlopen(‘http://httpbin.org/get‘, timeout=1)print(response.read())

运行之后我们看到可以正常的返回结果,接着我们将timeout时间设置为0.1
运行程序会提示错误socket.timeout:timed out 异常

对异常进行捕获

import urllib.requestimport socketimport urllib.errortry: ???response = urllib.request.urlopen(‘http://httpbin.org/get‘, timeout=1) ???print(response.read())except urllib.error.URLError as e: ???if isinstance(e.reason,socket.timeout): ???????print(‘time out‘)

  

request

设置Headers

有很多网站为了防止程序爬虫爬网站造成网站瘫痪,会需要携带一些headers头部信息才能访问,最长见的有user-agent参数

写一个简单的例子:

import urllib.requestrequest = urllib.request.Request(‘https://python.org‘)response = urllib.request.urlopen(request)print(response.read().decode(‘utf-8‘))

给请求添加头部信息,从而定制自己请求网站是时的头部信息

from urllib import request, parseurl = ‘http://httpbin.org/post‘headers = { ???‘User-Agent‘: ‘Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)‘, ???‘Host‘: ‘httpbin.org‘}dict = { ???‘name‘: ‘zhaofan‘}data = bytes(parse.urlencode(dict), encoding=‘utf8‘)req = request.Request(url=url, data=data, headers=headers, method=‘POST‘)response = request.urlopen(req)print(response.read().decode(‘utf-8‘))

添加请求头的第二种方式

from urllib import request, parseurl = ‘http://httpbin.org/post‘dict = { ???‘name‘: ‘Germey‘}data = bytes(parse.urlencode(dict), encoding=‘utf8‘)req = request.Request(url=url, data=data, method=‘POST‘)req.add_header(‘User-Agent‘, ‘Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)‘)response = request.urlopen(req)print(response.read().decode(‘utf-8‘))

这种添加方式有个好处是自己可以定义一个请求头字典,然后循环进行添加

URL解析

urlparse

from urllib.parse import urlparseresult = urlparse("http://www.baidu.com/index.html;user?id=5#comment")print(result)

这里就是可以对你传入的url地址进行拆分
同时我们是可以指定协议类型:
result = urlparse("www.baidu.com/index.html;user?id=5#comment",scheme="https")
这样拆分的时候协议类型部分就会是你指定的部分,当然如果你的url里面已经带了协议,你再通过scheme指定的协议就不会生效

urllib

原文地址:https://www.cnblogs.com/start20180703/p/10417460.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved