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爬取m3u8连接的视频

本文为大家分享了python爬取m3u8连接的视频方法,供大家参考,具体内容如下 要求:输入m3u8所在url,且ts视频与其在同一路径下 #!/usr/bin/env/pytho...

python爬虫 正则表达式使用技巧及爬取个人博客的实例讲解

python爬虫 正则表达式使用技巧及爬取个人博客的实例讲解

这篇博客是自己《数据挖掘与分析》课程讲到正则表达式爬虫的相关内容,主要简单介绍Python正则表达式爬虫,同时讲述常见的正则表达式分析方法,最后通过实例爬取作者的个人博客网站。希望这篇基...

Python爬取破解无线网络wifi密码过程解析

Python爬取破解无线网络wifi密码过程解析

前言 今天从WiFi连接的原理,再结合代码为大家详细的介绍如何利用python来破解WiFi。 Python真的是无所不能,原因就是因为Python有数目庞大的库,无数的现成的轮子,让你...

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

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

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

用Python爬取QQ音乐评论并制成词云图的实例

用Python爬取QQ音乐评论并制成词云图的实例

环境:Ubuntu16.4 python版本:3.6.4 库:wordcloud 这次我们要讲的是爬取QQ音乐的评论并制成云词图,我们这里拿周杰伦的等你下课来举例。 第一步:获取评论 我...