Python爬取数据保存为Json格式的代码示例

yipeiwu_com6年前Python爬虫

python爬取数据保存为Json格式

代码如下:

#encoding:'utf-8'
import urllib.request
from bs4 import BeautifulSoup
import os
import time
import codecs
import json
#找到网址
def getDatas():
  # 伪装
  header={'User-Agent':"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11"}
  # url="https://movie.douban.com/top250"
  url="file:///E:/scrapy/2018-04-27/movie/movie.html"
  ret=urllib.request.Request(url=url,headers=header)
  # 打开网页
  res=urllib.request.urlopen(ret)
  # 转化格式
  response=BeautifulSoup(res,'html.parser')
  # 找到想要数据的父元素
  datas=response.find_all('div',{'class':'item'})
  # print(datas)
  #创建存放数据的文件夹
  folder_name="output"
  if not os.path.exists(folder_name):
      os.mkdir(folder_name)
  # 定义文件
  current_time=time.strftime('%Y-%m-%d',time.localtime())
  file_name="move"+current_time+".json"
  # 文件路径
  file_path=folder_name+"/"+file_name
  for item in datas:
    # print(item)
    dict1={}
    dict1['rank']=item.find('div',{'class':'pic'}).find('em').get_text()
    dict1['title']=item.find('div',{'class':'info'}).find('div',{'class':'hd'}).find('a').find('span',{'class':'title'}).get_text()
    dict1['picUrl']=item.find('div',{'class':'pic'}).find('a').find('img').get('src')
    # print(picUrl)
    # 保存数据为json格式
    try:
      with codecs.open(file_path,'a',encoding="utf-8") as fp:
        fp.write(json.dumps(dict1,ensure_ascii=False)+",\n")
    except IOError as err:
      print('error'+str(err))
    finally:
      fp.close()
  pass
getDatas()
# 爬取数据

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【听图阁-专注于Python设计】的支持。如果你想了解更多相关内容请查看下面相关链接

相关文章

基python实现多线程网页爬虫

一般来说,使用线程有两种模式, 一种是创建线程要执行的函数, 把这个函数传递进Thread对象里,让它来执行. 另一种是直接从Thread继承,创建一个新的class,把线程执行的代码放...

python爬虫获取百度首页内容教学

python爬虫获取百度首页内容教学

由传智播客教程整理,我们这里使用的是python2.7.x版本,就是2.7之后的版本,因为python3的改动略大,我们这里不用它。现在我们尝试一下url和网络爬虫配合的关系,爬浏览器首...

python爬取51job中hr的邮箱

本文实例为大家分享了python爬取51job中hr的邮箱具体代码,供大家参考,具体内容如下 #encoding=utf8 import urllib2 import cookie...

使用Scrapy爬取动态数据

使用Scrapy爬取动态数据

对于动态数据的爬取,可以选择selenium和PhantomJS两种方式,本文选择的是PhantomJS。 网址: https://s.taobao.com/search?q=笔记本电...

windows7 32、64位下python爬虫框架scrapy环境的搭建方法

windows7 32、64位下python爬虫框架scrapy环境的搭建方法

适用于python 2.7 64位安装 一、操作系统:WIN7 64位 二、python版本:2.7 64位(scrapy目前不支持3.x) 不确定位数的,看图 三、安装相关软件(可以...