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爬取51job中hr的邮箱

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

python3通过selenium爬虫获取到dj商品的实例代码

先给大家介绍下python3 selenium使用 其实这个就相当于模拟人的点击事件来连续的访问浏览器。如果你玩过王者荣耀的话在2016年一月份的版本里面就有一个bug。 安卓手机下载...

python爬虫模拟浏览器的两种方法实例分析

python爬虫模拟浏览器的两种方法实例分析

本文实例讲述了python爬虫模拟浏览器的两种方法。分享给大家供大家参考,具体如下: 爬虫爬取网站出现403,因为站点做了防爬虫的设置 一、Herders 属性 爬取CSDN博客 i...

Python制作豆瓣图片的爬虫

Python制作豆瓣图片的爬虫

  前段时间自学了一段时间的Python,想着浓一点项目来练练手。看着大佬们一说就是爬了100W+的数据就非常的羡慕,不过对于我这种初学者来说,也就爬一爬图片。   我相信很多人的第一个...

Python3网络爬虫中的requests高级用法详解

Python3网络爬虫中的requests高级用法详解

本节我们再来了解下 Requests 的一些高级用法,如文件上传,代理设置,Cookies 设置等等。 1. 文件上传 我们知道 Reqeuests 可以模拟提交一些数据,假如有的网站需...