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

yipeiwu_com5年前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 爬虫一键爬取 淘宝天猫宝贝页面主图颜色图和详情图的教程

实例如下所示: import requests import re,sys,os import json import threading import pprint class s...

Python爬虫包BeautifulSoup实例(三)

一步一步构建一个爬虫实例,抓取糗事百科的段子 先不用beautifulsoup包来进行解析 第一步,访问网址并抓取源码 # -*- coding: utf-8 -*- # @Auth...

Python3爬虫学习之MySQL数据库存储爬取的信息详解

Python3爬虫学习之MySQL数据库存储爬取的信息详解

本文实例讲述了Python3爬虫学习之MySQL数据库存储爬取的信息。分享给大家供大家参考,具体如下: 数据库存储爬取的信息(MySQL) 爬取到的数据为了更好地进行分析利用,而之前将爬...

python爬虫框架scrapy实战之爬取京东商城进阶篇

前言 之前的一篇文章已经讲过怎样获取链接,怎样获得参数了,详情请看python爬取京东商城普通篇,本文将详细介绍利用python爬虫框架scrapy如何爬取京东商城,下面话不多说了,来看...

python高阶爬虫实战分析

关于这篇文章有几句话想说,首先给大家道歉,之前学的时候真的觉得下述的是比较厉害的东西,但是后来发现真的是基础中的基础,内容还不是很完全。再看一遍自己写的这篇文章,突然有种想自杀的冲动。e...