python数据爬下来保存的位置

作者:十一月的萧邦。 时间:2021-01-29 20:49:19 

昨天下班后忽然兴起想写一个爬虫抓抓网页上的东西。花了一个钟简单学习了python的基础语法,然后参照网上的例子自己写了个爬虫。

python数据爬下来保存在本地,一般是文件或数据库中,但是文件形式相比要更加简单,如果只是自己写爬虫玩,可以用文件形式来保存数据。


#coding=utf-8
import urllib.request
import re
import os

'''
Urllib 模块提供了读取web页面数据的接口,我们可以像读取本地文件一样读取www和ftp上的数据
urlopen 方法用来打开一个url
read方法 用于读取Url上的数据
'''

def getHtml(url):
 page = urllib.request.urlopen(url);
 html = page.read();
 return html;

def getImg(html):
 imglist = re.findall('img src="(http.*?)"',html
 return imglist

html = getHtml("https://www.zhihu.com/question/34378366").decode("utf-8");
imagesUrl = getImg(html);

if os.path.exists("D:/imags") == False:
 os.mkdir("D:/imags");

count = 0;
for url in imagesUrl:
 print(url)
 if(url.find('.') != -1):
   name = url[url.find('.',len(url) - 5):];
   bytes = urllib.request.urlopen(url);
   f = open("D:/imags/"+str(count)+name, 'wb');
   f.write(bytes.read());
   f.flush();
   f.close();
   count+=1

经测试,基本功能还是可以实现的。花的较多的时间就是正则匹配哪里,因为自己对正则表达式也不是非常熟悉。所以还是花了点时间。

注:上面的程序基于 python 3.5。python3 和 python2 还是有些区别的。我刚开始看基础语法的时候就栽了一些坑里。

来源:https://blog.csdn.net/weixin_45625815/article/details/103734658

标签:python,数据保存
0
投稿

猜你喜欢

  • python中随机函数random用法实例

    2023-02-09 22:13:10
  • Python3实现从文件中读取指定行的方法

    2021-01-06 04:18:17
  • 如何利用python实现列表嵌套字典取值

    2023-07-08 02:16:50
  • 浅谈Python数据处理csv的应用小结

    2021-06-10 01:40:41
  • 一个比较完美的spacer div技巧

    2009-03-18 19:29:00
  • python语言线程标准库threading.local解读总结

    2023-12-22 18:18:07
  • 使用Python的SymPy库解决数学运算问题的方法

    2021-04-19 19:36:35
  • django将网络中的图片,保存成model中的ImageField的实例

    2023-12-23 01:11:33
  • 粗暴解决CUDA out of memory的问题

    2023-05-12 05:40:00
  • Python Spyder 调出缩进对齐线的操作

    2023-07-17 00:56:04
  • 网页制作,改变你的思维方式

    2007-09-29 13:12:00
  • 一些让Python代码简洁的实用技巧总结

    2022-02-06 11:03:25
  • 设计MySQL数据库的技巧

    2009-09-06 11:56:00
  • Python中的flask框架详解

    2021-03-20 20:23:59
  • python自动化办公操作PPT的实现

    2023-06-14 03:43:47
  • PHP5中使用DOM控制XML实现代码

    2023-09-30 09:00:07
  • OpenCV-Python实现油画效果的实例

    2022-03-26 09:16:37
  • selenium+python实现文件上传操作的方法实例

    2022-05-06 13:21:49
  • Jquery实现div模拟Select控件

    2008-12-01 15:47:00
  • 使用pth文件添加Python环境变量方式

    2023-02-27 06:10:03
  • asp之家 网络编程 m.aspxhome.com