Python3学习urllib的使用方法示例
作者:Data&Truth 发布时间:2021-09-23 00:08:08
urllib是python的一个获取url(Uniform Resource Locators,统一资源定址符)了,可以利用它来抓取远程的数据进行保存,本文整理了一些关于urllib使用中的一些关于header,代理,超时,认证,异常处理处理方法。
1.基本方法
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
url: 需要打开的网址
data:Post提交的数据
timeout:设置网站的访问超时时间
直接用urllib.request模块的urlopen()获取页面,page的数据格式为bytes类型,需要decode()解码,转换成str类型。
from urllib import request
response = request.urlopen(r'http://python.org/') # <http.client.HTTPResponse object at 0x00000000048BC908> HTTPResponse类型
page = response.read()
page = page.decode('utf-8')
urlopen返回对象提供方法:
read() , readline() ,readlines() , fileno() , close() :对HTTPResponse类型数据进行操作
info():返回HTTPMessage对象,表示远程服务器返回的头信息
getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到
geturl():返回请求的url
1、简单读取网页信息
import urllib.request
response = urllib.request.urlopen('http://python.org/')
html = response.read()
2、使用request
urllib.request.Request(url, data=None, headers={}, method=None)
使用request()来包装请求,再通过urlopen()获取页面。
import urllib.request
req = urllib.request.Request('http://python.org/')
response = urllib.request.urlopen(req)
the_page = response.read()
3、发送数据,以登录知乎为例
'''''
Created on 2016年5月31日
@author: gionee
'''
import gzip
import re
import urllib.request
import urllib.parse
import http.cookiejar
def ungzip(data):
try:
print("尝试解压缩...")
data = gzip.decompress(data)
print("解压完毕")
except:
print("未经压缩,无需解压")
return data
def getXSRF(data):
cer = re.compile('name=\"_xsrf\" value=\"(.*)\"',flags = 0)
strlist = cer.findall(data)
return strlist[0]
def getOpener(head):
# cookies 处理
cj = http.cookiejar.CookieJar()
pro = urllib.request.HTTPCookieProcessor(cj)
opener = urllib.request.build_opener(pro)
header = []
for key,value in head.items():
elem = (key,value)
header.append(elem)
opener.addheaders = header
return opener
# header信息可以通过firebug获得
header = {
'Connection': 'Keep-Alive',
'Accept': 'text/html, application/xhtml+xml, */*',
'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0',
'Accept-Encoding': 'gzip, deflate',
'Host': 'www.zhihu.com',
'DNT': '1'
}
url = 'http://www.zhihu.com/'
opener = getOpener(header)
op = opener.open(url)
data = op.read()
data = ungzip(data)
_xsrf = getXSRF(data.decode())
url += "login/email"
email = "登录账号"
password = "登录密码"
postDict = {
'_xsrf': _xsrf,
'email': email,
'password': password,
'rememberme': 'y'
}
postData = urllib.parse.urlencode(postDict).encode()
op = opener.open(url,postData)
data = op.read()
data = ungzip(data)
print(data.decode())
4、http错误
import urllib.request
req = urllib.request.Request('http://www.lz881228.blog.163.com ')
try:
urllib.request.urlopen(req)
except urllib.error.HTTPError as e:
print(e.code)
print(e.read().decode("utf8"))
5、异常处理
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request("http://www.abc.com /")
try:
response = urlopen(req)
except HTTPError as e:
print('The server couldn't fulfill the request.')
print('Error code: ', e.code)
except URLError as e:
print('We failed to reach a server.')
print('Reason: ', e.reason)
else:
print("good!")
print(response.read().decode("utf8"))
6、http认证
import urllib.request
# create a password manager
password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of None.
top_level_url = "https://www.jb51.net /"
password_mgr.add_password(None, top_level_url, 'rekfan', 'xxxxxx')
handler = urllib.request.HTTPBasicAuthHandler(password_mgr)
# create "opener" (OpenerDirector instance)
opener = urllib.request.build_opener(handler)
# use the opener to fetch a URL
a_url = "https://www.jb51.net /"
x = opener.open(a_url)
print(x.read())
# Install the opener.
# Now all calls to urllib.request.urlopen use our opener.
urllib.request.install_opener(opener)
a = urllib.request.urlopen(a_url).read().decode('utf8')
print(a)
7、使用代理
import urllib.request
proxy_support = urllib.request.ProxyHandler({'sock5': 'localhost:1080'})
opener = urllib.request.build_opener(proxy_support)
urllib.request.install_opener(opener)
a = urllib.request.urlopen("http://www.baidu.com ").read().decode("utf8")
print(a)
8、超时
import socket
import urllib.request
# timeout in seconds
timeout = 2
socket.setdefaulttimeout(timeout)
# this call to urllib.request.urlopen now uses the default timeout
# we have set in the socket module
req = urllib.request.Request('https://www.jb51.net /')
a = urllib.request.urlopen(req).read()
print(a)
来源:https://www.cnblogs.com/Lands-ljk/p/5447127.html


猜你喜欢
- UEditor效果图一、简介UEditor是一个开源免费的编辑器,由百度web前端研发部开发所见即所得富文本web编辑器,具有轻量,可定制,
- 什么是闭包:闭包是一个存在内部函数的引用关系。该引用指向的是外部函数的局部变量对象(前提是内部函数使用了外部函数的局部变量)闭包的作用:延长
- 当我发现要写python的面向对象的时候,我是踌躇满面,坐立不安呀。我一直在想:这个坑应该怎么爬?因为python中关于面向对象的内容很多,
- 假设现有需求如下:需要一个页面分页展示信息,在该页面添加搜索框以提供检索功能。那么,我们知道,展示信息和检索功能是在同一个页面,也就是共用一
- 摘要:本文介绍HetuEngine实现On Yarn的原理,通过阅读本文,读者可以了解HetuEngine如何在资源使用方面融入Hadoop
- 1. 什么是存储过程?存储过程是SQL server所提供的Tran
- python strip() 函数和 split() 函数的详解及实例一直以来都分不清楚strip和split的功能,实际上st
- MySQL有时候忘记了root密码是一件伤感的事,这种情况下,如何重置root的密码呢?找到并编辑mysql的my.ini配置文件,在mys
- 上一次的错误太多,排版也出现了问题,重写了一遍,希望大家支持.循环遍历一个元素是开发中最常见的需求之一,那么让我们来看一个由框架BASE2和
- 定义线程最简单的方法:使用target指定线程要执行的目标函数,再使用start()启动。语法:class threading.Thread
- 本文实例讲述了Python动态生成多维数组的方法。分享给大家供大家参考,具体如下:多维数组其实就是多个一维数组的嵌套,Python中有原生的
- 一、爬虫的简单理解1. 什么是爬虫?网络爬虫也叫网络蜘蛛,如果把互联网比喻成一个蜘蛛网,那么蜘蛛就是在网上爬来爬去的蜘蛛,爬虫程序通过请求u
- 前言PyCharm是一种Python 的IDE工具(集成开发环境),带有一整套可以帮助用户在使用Python语言开发时提高其效率的工具,内部
- 1、说明装饰本质上是一个Python函数,它能使其他函数在没有任何代码变化的情况下增加额外的功能。有了装饰,我们可以抽出大量与函数功能无关的
- 1.安装相应的库文件sudo apt-get install python-mysqldb2.数据库操作import MySQLdb db
- 如下所示:func Caller(skip int) (pc uintptr, file string, line int, ok bool
- 在SQL语句优化过程中,我们经常会用到hint,现总结一下在SQL优化过程中常见Oracle HINT的用法:1. /*+ALL_ROWS*
- 许多游戏玩家一定会对游戏中的动态鼠标指针有很深的印象,其实只要一句简单的CSS(层叠样式表),你也能在网页上实现这种效果。首先,你需要一个鼠
- Analyze Table MySQL 的Optimizer(优化元件)在优化SQL语句时,首先需要收集一些相关信息,其中就包括表的card
- 本文实例讲述了Python按行读取文件的实现方法。分享给大家供大家参考,具体如下:小文件:#coding=utf-8#author: wal