#urllib从如入门到放弃
#导入urllib模块
import urllib.request
#使用urlopen函数读取目标地址
def getHtml():
bd = urllib.request.urlopen('http://www.douban.com')
# 获取网页响应返回的应答码
# respcode = bd.getcode()
# print(respcode)
# 打印获取到的全部内容
# html = bd.read()
# print(html)
# 只读100字节
# html = bd.read(100)
# print(html)
# 只读一行
# html = bd.readline()
# print(html)
# 返回一个列表,使用下面定义的print_list方法进行打印。(请打开print_list()方法食用。QAQ)
# lines = bd.readlines()
# print_list(lines)
#打印指定行数数据
# for i in range(10):
# html = bd.readline()
# print('line %d:%s'%(i+1,html))
#info()方法,获取响应头部信息
#info = bd.info()
# print(info)
#应该是python2.x中的方法,用于获取content-Type
# print(info.getheader('content-Type')) #Error:(AttributeError: 'HTTPMessage' object has no attribute 'getheader')
#应该是python2.x中的方法
# print(info.headers) #Error:(AttributeError: 'HTTPMessage' object has no attribute 'headers')
#利用dir()方法可以得知在python3.x中想要获取content-Type应该使用get_content_type.YES(returned:text/html).
# print(info.get_content_type())
# 调试技巧
# 返回结果是一个列表,因此可以用下面定义好的print_list()方法打印出来,查看info可以调用的方法。
# methods = dir(info)
# 调用该方法前,请打开该方法
# print_list(methods)
#读取为列表时设置一个打印列表的函数
# def print_list(linelist):
# for i in linelist:
# print(i)
#利用retrieve方法进行下载
def retrieve():
# AttributeError: module 'urllib' has no attribute 'urlretrieve'
# python2中的方法
# urllib.urlretrieve('hppt://book.douban.com','cart.html')
# python3中利用urllib库中request下的urlretrieve()方法。(参数1:目标页面,参数二:生成的页面名字)
# 该方法返回的是文件名以及一个html对象
urllib.request.urlretrieve('http://book.douban.com','bookdouban.html')
# 该方法返回的是文件名以及一个html对象,进行验证
# file_name,obj_html=urllib.request.urlretrieve('http://book.douban.com','bookdouban.html')
# print(file_name)
# print(obj_html)
# 以列表形式展现,但是没必要啊!!!
# print(obj_html.items())
# reporthook(),该方法又三个参数(参数1:当前传输块数量;参数2:块的大小;参数3:数据的总大小)
# 用来监控下载进度
# TypeError: reporthooktest() missing 3 required positional arguments: 'block_num', 'block_size', and 'total_size'
# 事实证明这个方法只有教程视频的那个大佬会用,可能是python2的方法,python3已经废弃?
# reporthook应该是urlretrieve下的一个方法
# def reporthooktest(block_num,block_size,total_size):
# print('%d/%d-%.02f%%' % (block_num*block_size,total_size,(float)(block_size*block_num)*100/total_size))
#主函数入口
if __name__ == '__main__':
# 获取目标html信息
# getHtml()
# 利用retrieve方法进行下载
retrieve()
# 一个测试不出来的方法
# reporthooktest()
爬虫基础urllib库了解
最新推荐文章于 2024-09-30 09:48:55 发布