281day(基本库urllib复习)

本文详细介绍了Python标准库中Urllib模块的功能与用法,包括urllib.request.urlopen()方法的data和timeout参数设置、Request对象创建、BaseHandler类的使用、urlparse()函数解析URL以及robotparser处理robots.txt文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

《2018年7月10日》【连续281天】

标题:基本库urllib复习;

内容:

复习一波基本库:

1.urllib:

a.

urllib.request.urlopen()

data参数:缺省,使用后请求方法就是post了,

测试:
import urllib.parse
import urllib.request

data =bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8')
response =urllib.request.urlopen('http://httpbin.org/post',data=data)
print(response.read())
timeout参数:
测试:
try:
    response =urllib.request.urlopen('http://httpbin.org/get',timeout=0.1)
    print(response.read())
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout):
        print('TIME OUT')
b.request:
request =urllib.request.Request('https://python.org')
response =urllib.request.urlopen(request)

c.BaseHandler类,所有Handler类的父类

OpenerDirector;

通过Handler和opener的高级用法,来处理密码验证,代理,Cookies等;


d.urlparse():实现url的识别和分段;

from urllib.parse import urlparse

result =urlparse('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result), result)

输出:

<class 'urllib.parse.ParseResult'> ParseResult(scheme='http', netloc='www.baidu.com', path='/index.html', params='user', query='id=5', fragment='comment')

有三个参数:

urlstring:url

scheme:缺省的协议

allow_fragments:是否忽略fragment,缺省为Ture;


e.

robotparser:解析robot.txt

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值