当前位置:首页 » python爬虫 » 正文

python数据爬下来保存的位置

看: 871次  时间:2020-08-13  分类 : python爬虫

昨天下班后忽然兴起想写一个爬虫抓抓网页上的东西。花了一个钟简单学习了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 还是有些区别的。我刚开始看基础语法的时候就栽了一些坑里。

以上就是python数据爬下来保存在哪里的详细内容,感谢大家的学习和对python博客的支持。

标签:urllib  

<< 上一篇 下一篇 >>

搜索

推荐资源

  Powered By python教程网   鲁ICP备18013710号
python博客 - 小白学python最友好的网站!