python中urllib模块使用

目录

一:访问url

二:发送参数

三:发送带header的参数

四:发送超时时间

五:发送代理服务请求

六:发送认证服务请求


在Python 3中,urllib2模块已被重命名为urllib。在python2中,你可以使用urllib2。

一:访问url

import urllib.request  
  
response = urllib.request.urlopen('http://www.baidu.com')  
data = response.read()
print(data)

二:发送参数

import urllib.request  
import urllib.parse  
  
data = {'key1': 'value1', 'key2': 'value2'}  
post_data = urllib.parse.urlencode(data)  
  
with urllib.request.urlopen('http://www.baidu.com', post_data) as response:  
    data = response.read()
    print(data)

三:发送带header的参数

import urllib.request  
  
url = 'http://www.baidu.com'  
data = {'key1': 'value1', 'key2': 'value2'}  
headers = {'User-Agent': 'Mozilla/5.0'}  
  
# 发送GET请求  
req = urllib.request.Request(url, data, headers)  
response = urllib.request.urlopen(req)  
data = response.read()  
print(data)

四:发送超时时间


import urllib.request  
  
url = 'http://www.baidu.com'  
timeout = 10  # 设置超时时间为10秒  
  
try:  
    response = urllib.request.urlopen(url, timeout=timeout)  
    data = response.read()  
    print(data)  
except urllib.request.URLError as e:  
    print(f"Error: {e.reason}")

五:发送代理服务请求

import urllib.request  
import urllib.error  
  
# 代理服务器设置  
proxy_handler = urllib.request.ProxyHandler({'http': 'http://proxy.baidu.com:8080'})  
  
# 创建未处理HTTP错误的处理程序  
http_error_handler = urllib.request.HTTPDefaultErrorHandler()  
  
# 创建自定义的处理器,包括代理处理器和错误处理器  
opener = urllib.request.build_opener(proxy_handler, http_error_handler)  
  
# 使用自定义的处理器发送请求  
try:  
    response = opener.open('http://www.baidu.com')  
    data = response.read()  
    print(data)  
except urllib.error.HTTPError as e:  
    print(f"Error: {e.code} {e.reason}")

六:发送认证服务请求

import urllib.request  
import urllib.error  
  
# 认证信息  
username = 'your_username'  
password = 'your_password'  
  
# 创建认证处理器  
auth_handler = urllib.request.HTTPBasicAuthHandler()  
auth_handler.add_password(realm='Authentication Required',  
                          uri='http://www.baidu.com',  
                          user=username,  
                          passwd=password)  
  
# 创建自定义的处理器,包括认证处理器和错误处理器  
opener = urllib.request.build_opener(auth_handler)  
  
# 使用自定义的处理器发送请求  
try:  
    response = opener.open('http://www.baidu.com')  
    data = response.read()  
    print(data)  
except urllib.error.HTTPError as e:  
    print(f"Error: {e.code} {e.reason}")

  • 14
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

攻城狮的梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值