Python基于pandas实现json格式转换成dataframe的方法


Posted in Python onJune 22, 2018

本文实例讲述了Python基于pandas实现json格式转换成dataframe的方法。分享给大家供大家参考,具体如下:

# -*- coding:utf-8 -*-
#!python3
import re
import json
from bs4 import BeautifulSoup
import pandas as pd
import requests
import os
from pandas.io.json import json_normalize
class image_structs():
  def __init__(self):
    self.picture_url = {
      "image_id": '',
      "picture_url": ''
    }
class data_structs():
  def __init__(self):
    # columns=['title', 'item_url', 'id','picture_url','std_desc','description','information','fitment'])
    self.info={
      "title":'',
      "item_url":'',
      "id":0,
      "picture_url":[],
      "std_desc":'',
      "description":'',
      "information":'',
      "fitment":''
    }
# "https://waldoch.com/store/catalogsearch/result/index/?cat=0&limit=200&p=1&q=nerf+bar"
# https://waldoch.com/store/new-oem-ford-f-150-f150-5-running-boards-nerf-bar-crew-cab-2015-w-brackets-fl34-16451-ge5fm6.html
def get_item_list(outfile):
  result = []
  for i in range(6):
    print(i)
    i = str(i+1)
    url = "https://waldoch.com/store/catalogsearch/result/index/?cat=0&limit=200&p="+i+"&q=nerf+bar"
    web = requests.get(url)
    soup = BeautifulSoup(web.text,"html.parser")
    alink = soup.find_all("a",class_="product-image")
    for a in alink:
      title = a["title"]
      item_url = a["href"]
      result.append([title,item_url])
  df = pd.DataFrame(result,columns=["title","item_url"])
  df = df.drop_duplicates()
  df["id"] =df.index
  df.to_excel(outfile,index=False)
def get_item_info(file,outfile):
  DEFAULT_FALSE = ""
  df = pd.read_excel(file)
  for i in df.index:
    id = df.loc[i,"id"]
    if os.path.exists(str(int(id))+".xlsx"):
      continue
    item_url = df.loc[i,"item_url"]
    url = item_url
    web = requests.get(url)
    soup = BeautifulSoup(web.text, "html.parser")
    # 图片
    imglink = soup.find_all("img", class_=re.compile("^gallery-image"))
    data = data_structs()
    data.info["title"] = df.loc[i,"title"]
    data.info["id"] = id
    data.info["item_url"] = item_url
    for a in imglink:
      image = image_structs()
      image.picture_url["image_id"] = a["id"]
      image.picture_url["picture_url"]=a["src"]
      print(image.picture_url)
      data.info["picture_url"].append(image.picture_url)
    print(data.info)
    # std_desc
    std_desc = soup.find("div", itemprop="description")
    try:
      strings_desc = []
      for ii in std_desc.stripped_strings:
        strings_desc.append(ii)
      strings_desc = "\n".join(strings_desc)
    except:
      strings_desc=DEFAULT_FALSE
    # description
    try:
      desc = soup.find('h2', text="Description")
      desc = desc.find_next()
    except:
      desc=DEFAULT_FALSE
    description=desc
    # information
    try:
      information = soup.find("h2", text='Information')
      desc = information
      desc = desc.find_next()
    except:
      desc=DEFAULT_FALSE
    information = desc
    # fitment
    try:
      fitment = soup.find('h2', text='Fitment')
      desc = fitment
      desc = desc.find_next()
    except:
      desc=DEFAULT_FALSE
    fitment=desc
    data.info["std_desc"] = strings_desc
    data.info["description"] = str(description)
    data.info["information"] = str(information)
    data.info["fitment"] = str(fitment)
    print(data.info.keys())
    singledf = json_normalize(data.info,"picture_url",['title', 'item_url', 'id', 'std_desc', 'description', 'information', 'fitment'])
    singledf.to_excel("test.xlsx",index=False)
    exit()
    # print(df.ix[i])
  df.to_excel(outfile,index=False)
# get_item_list("item_urls.xlsx")
get_item_info("item_urls.xlsx","item_urls_info.xlsx")

这里涉及到的几个Python模块都可以使用pip install命令进行安装,如:

pip install BeautifulSoup4
pip install xlrd
pip install openpyxl
Python 相关文章推荐
python实现监控linux性能及进程消耗性能的方法
Jul 25 Python
提升Python程序运行效率的6个方法
Mar 31 Python
在Django的视图中使用数据库查询的方法
Jul 16 Python
python去除空格和换行符的实现方法(推荐)
Jan 04 Python
基于python OpenCV实现动态人脸检测
May 25 Python
django从请求到响应的过程深入讲解
Aug 01 Python
windows下cx_Freeze生成Python可执行程序的详细步骤
Oct 09 Python
Python 常用模块 re 使用方法详解
Jun 06 Python
django实现HttpResponse返回json数据为中文
Mar 27 Python
python_matplotlib改变横坐标和纵坐标上的刻度(ticks)方式
May 16 Python
使用python脚本自动生成K8S-YAML的方法示例
Jul 12 Python
Python日志打印里logging.getLogger源码分析详解
Jan 17 Python
深入浅析Python的类
Jun 22 #Python
基于python绘制科赫雪花
Jun 22 #Python
python3读取csv和xlsx文件的实例
Jun 22 #Python
django admin 后台实现三级联动的示例代码
Jun 22 #Python
python使用turtle库与random库绘制雪花
Jun 22 #Python
Python3导入CSV文件的实例(跟Python2有些许的不同)
Jun 22 #Python
Django Admin实现三级联动的示例代码(省市区)
Jun 22 #Python
You might like
PHP 数组入门教程小结
2009/05/20 PHP
PHP 一个比较完善的简单文件上传
2010/03/25 PHP
PHP学习笔记之二 php入门知识
2011/01/12 PHP
php 短链接算法收集与分析
2011/12/30 PHP
Fedora下安装php Redis扩展笔记
2014/09/03 PHP
php实现XSS安全过滤的方法
2015/07/29 PHP
完美解决thinkphp唯一索引重复时出错的问题
2017/03/31 PHP
php lcg_value与mt_rand生成0~1随机小数的效果对比分析
2017/04/05 PHP
php实现的证件照换底色功能示例【人像抠图/换背景图】
2020/05/29 PHP
jQuery 中使用JSON的实现代码
2011/12/01 Javascript
javascript中不等于的代码是什么怎么写
2013/12/29 Javascript
分享9点个人认为比较重要的javascript 编程技巧
2015/04/27 Javascript
jquery分析文本里url或邮件地址为真实链接的方法
2015/06/20 Javascript
纯javascript实现分页(两种方法)
2015/08/26 Javascript
jquery选择器简述
2015/08/31 Javascript
jquery 校验中国身份证号码实例详解
2017/04/11 jQuery
解决Extjs下拉框不显示的问题
2017/06/21 Javascript
jQuery绑定事件方法及区别(bind,click,on,live,one)
2017/08/14 jQuery
详解Vue路由History mode模式中页面无法渲染的原因及解决
2017/09/28 Javascript
[04:03][TI9趣味短片] 小鸽子茶话会
2019/08/20 DOTA
[01:38]完美世界DOTA2联赛(PWL)宣传片:第一站
2020/10/26 DOTA
[03:12]完美世界DOTA2联赛PWL DAY9集锦
2020/11/10 DOTA
在Python程序中实现分布式进程的教程
2015/04/28 Python
Python3连接MySQL(pymysql)模拟转账实现代码
2016/05/24 Python
python 字典item与iteritems的区别详解
2020/04/25 Python
JAVA SWT事件四种写法实例解析
2020/06/05 Python
Python scrapy爬取小说代码案例详解
2020/07/09 Python
Pycharm无法打开双击没反应的问题及解决方案
2020/08/17 Python
德国家用电器购物网站:Premiumshop24
2019/08/22 全球购物
党校学习自我鉴定
2014/02/24 职场文书
小区文明倡议书
2014/05/16 职场文书
高中学生自我评价范文
2014/09/23 职场文书
暑假社会实践证明格式
2014/10/28 职场文书
党员倡议书
2015/01/19 职场文书
第一节英语课开场白
2015/06/01 职场文书
python自动化测试通过日志3分钟定位bug
2021/11/20 Python