使用python实现简单爬虫
来源:互联网 发布:网站sql注入检测 编辑:程序博客网 时间:2024/05/19 11:46
近日学习了python语言,简单实现了一个爬虫,爬取了慕课网课程简介上的图片,并保存到本地。以下是实验代码:
# -*- coding: utf-8 -*-"""Spyder Editor"""import reimport osimport urllib.request #在python3.6环境中实现f_soure = urllib.request.urlopen('http://www.imooc.com/course/list')#爬取目标地址mybytes = f_soure.read()mystr = mybytes.decode('utf8')result = re.findall(r'http:.+\.jpg',mystr)#打印输出并对正则结果进行字符串切割print(len(result[0]))print(result[0].index('.jpg'))print(result[0][:60])l = []for i in result: l.append(i[:60])print (l)#重新生成图片url地址,读出并保存到本地k=0for url in l: f = open('F:\\python_test\\%d.jpg'%(k),'wb+') rep = urllib.request.urlopen(url) f.write(rep.read()) f.close() k+=1 print ('success')
在实验过程中,发现使用python自带的os模块,当urllib.request.urlopen(url)方法返回的类file对象时,使用此对象的read方法会出现读取不完全现象。代码如下:
# -*- coding: utf-8 -*-"""Spyder Editor"""import reimport urllib.requestf_soure = urllib.request.urlopen('http://www.imooc.com/course/list')mybytes = f_soure.read()mystr = mybytes.decode('utf8')result = re.findall(r'http:.+\.jpg',mystr)print(len(result[0]))print(result[0].index('.jpg'))print(result[0][:60])l = []for i in result: l.append(i[:60])print (l)k=0#使用os模块进行写入for url in l: f = os.open('F:\\python_test\\%d.jpg'%(k),os.O_CREAT|os.O_RDWR) rep = urllib.request.urlopen(url) iter_f = iter(rep) for line in iter_f: os.write(f,line) os.close(f) k+=1 print ('success')
如果有大神知道为什么这样,还请解惑~~
阅读全文
0 0
- 使用python实现简单爬虫
- 使用python实现简单爬虫
- python 简单爬虫实现
- Python实现简单爬虫
- Python实现简单爬虫
- Python实现简单爬虫
- Python实现简单爬虫
- python 实现简单爬虫
- Python简单爬虫实现
- python 爬虫简单使用
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- python 实现简单网络爬虫
- Python实现简单的爬虫
- python实现简单爬虫功能
- Linux内核源代码获取方法
- c/c++中sizeof()、strlen()、length()、size()详解和区别
- 一个打了激素的数组01--2017/08/30--1
- Git GUI的使用
- 第六十三篇:common-compress压缩解压文件
- 使用python实现简单爬虫
- [FAQ11783][NW]MVNO忽略国内漫游(ignore national roaming)
- UART
- Tensorflow入门-实现神经网络
- CAD导出JPG格式什么像素最清晰
- 转发技术风雨三十年,你经历过……
- echart使用记录——版本2和3的一些区别
- ORACLE日期转换成汉字某年某月某日
- linux中查找包含某关键字的文件