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
猜你喜欢
- show tables或show tables from database_name;解释:显示当前数据库中所有表的名称show datab
- 摘要:有时候我们只需要数据集中的一部分,并不需要全部的数据。这个时候我们就要对数据集进行随机的抽样。pandas中自带有抽样的方法。应用场景
- 本文实例为大家分享了Python爬取最好大学网大学排名的具体代码,供大家参考,具体内容如下源代码:#-*-coding:utf-8-*- &
- 我们日常用CSS布局的时候,关于图片背景,大部分的人都是一个背景一张图片的,怎么说呢?这是很标准的方法,但是这种普通制作方式下要保存大量图片
- 用实例来说明 import 的作用吧。创建以下包结构。一个文件夹 cookFish/,下面包含两个文件, __init__.py和cookB
- 大家好,今天给大家分享一下明哥整理的一篇 Python 参数的内容,内容非常的干,全文通过案例的形式来理解知识点,自认为比网上 80% 的文
- 需求:从服务器拷贝照片到本地,然后再从本地照片筛选照片。问题:从服务器拷贝到照片本地,太慢,速度只有20~30K,不能忍。然后想到,利用py
- 作者:xiaolanLin声明 :本文版权归作者和博客园共有,来源网址:https://www.cnblogs.com/xiaolan-Li
- # -*- coding: utf8 -*- #! python print(repr("测试报警,xxxx是大猪头".
- 最近在研究雨哲软件采集程序的时候,需要获取真实软件地址时遇到了需要读取跳转页面跳转后的真实地址的问题。在网上找了很多方法,使用WinHttp
- 自定义数据库字段扩展默认的models.CharField和models.TextField使之成为支持多语言的字段。可以轻松实现复用,无需
- 内容摘要:图片切换效果在网页制作中经常被使用,好的切换效果不仅增加了网站的实用行也提升了网站的趣味性。而图片切换方法有的使用flash来实现
- python 是一门优雅的语言,有些使用方法就像魔法一样。装饰器(decorator)就是一种化腐朽性为神奇的技巧。最近一直都在使用 Tor
- python中with可以明显改进代码友好度,比如:with open('a.txt') as f:  
- reader.html<html><head><meta http-equiv=&quo
- 运行效果:完整代码from tkinter import *def click(num): global op op
- 打开在节点中加入一句:max_allowed_packet=5M 将MySQL的容量扩大到5M  
- 相信用过Gmail的人都知道Gmail有一个草稿自动保存的功能,每过一段时间,Gmail都会自动保存邮件草稿,这样在一些突 * 况下就能快速地
- 在 python 中有一个 telnetlib,它的作用就是建立一个通到主机的 telnet连线实体
- 前言一道题目是实现一个反转字符串的函数,具体如下:编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给