Python3中使用urllib的方法详解(header,代理,超时,认证,异常处理)
作者:ifso 时间:2023-10-20 19:36:33
我们可以利用urllib来抓取远程的数据进行保存哦,以下是python3 抓取网页资源的多种方法,有需要的可以参考借鉴。
1、最简单
import urllib.request
response = urllib.request.urlopen('http://python.org/')
html = response.read()
2、使用 Request
import urllib.request
req = urllib.request.Request('http://python.org/')
response = urllib.request.urlopen(req)
the_page = response.read()
3、发送数据
#! /usr/bin/env python3
import urllib.parse
import urllib.request
url = 'http://localhost/login.php'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {
'act' : 'login',
'login[email]' : 'yzhang@i9i8.com',
'login[password]' : '123456'
}
data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data)
req.add_header('Referer', 'http://www.python.org/')
response = urllib.request.urlopen(req)
the_page = response.read()
print(the_page.decode("utf8"))
4、发送数据和header
#! /usr/bin/env python3
import urllib.parse
import urllib.request
url = 'http://localhost/login.php'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {
'act' : 'login',
'login[email]' : 'yzhang@i9i8.com',
'login[password]' : '123456'
}
headers = { 'User-Agent' : user_agent }
data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
the_page = response.read()
print(the_page.decode("utf8"))
5、http 错误
#! /usr/bin/env python3
import urllib.request
req = urllib.request.Request('https://www.jb51.net ')
try:
urllib.request.urlopen(req)
except urllib.error.HTTPError as e:
print(e.code)
print(e.read().decode("utf8"))
6、异常处理1
#! /usr/bin/env python3
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request("https://www.jb51.net /")
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"))
7、异常处理2
#! /usr/bin/env python3
from urllib.request import Request, urlopen
from urllib.error import URLError
req = Request("https://www.jb51.net /")
try:
response = urlopen(req)
except URLError as e:
if hasattr(e, 'reason'):
print('We failed to reach a server.')
print('Reason: ', e.reason)
elif hasattr(e, 'code'):
print('The server couldn't fulfill the request.')
print('Error code: ', e.code)
else:
print("good!")
print(response.read().decode("utf8"))
8、HTTP 认证
#! /usr/bin/env python3
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)
9、使用代理
#! /usr/bin/env python3
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("https://www.jb51.net ").read().decode("utf8")
print(a)
10、超时
#! /usr/bin/env python3
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)
总结
标签:python3,urllib
0
投稿
猜你喜欢
pytorch cnn 识别手写的字实现自建图片数据
2023-04-18 02:39:22
对Django的restful用法详解(自带的增删改查)
2023-11-12 07:45:04
mysql命令行爱好者必备工具mycli
2024-01-24 13:33:33
对python中的乘法dot和对应分量相乘multiply详解
2021-01-14 15:54:58
windows 7安装ORACLE 10g客户端的方法分享
2012-07-11 15:36:18
详解Golang中select的使用与源码分析
2024-05-09 14:52:08
Python面向对象编程之封装的艺术你了解吗
2022-04-26 22:07:24
java正则表达式之Pattern与Matcher类详解
2023-06-21 10:14:03
详解如何在Apache中运行Python WSGI应用
2021-05-16 05:24:03
基于vue-resource jsonp跨域问题的解决方法
2023-07-02 16:33:44
Python字符串、元组、列表、字典互相转换的方法
2022-10-28 20:25:51
HTTP中header头部信息详解
2023-06-11 23:33:17
python爬虫 批量下载zabbix文档代码实例
2022-11-07 11:10:29
perl uc,lc,ucfirst,lcfirst大小写转换函数
2023-11-14 01:12:02
Python爬虫开发与项目实战
2022-04-21 03:10:32
python热力图实现简单方法
2023-10-28 06:14:41
Python实现CET查分的方法
2023-06-13 12:05:51
python命令行参数argparse模块基本用法详解
2023-07-31 03:14:21
Yii2中的场景(scenario)和验证规则(rule)详解
2024-04-28 09:43:50
python实现定时压缩指定文件夹发送邮件
2022-06-02 19:32:36