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中的文件和目录操作实现代码
Mar 13 Python
python中的多线程实例教程
Aug 27 Python
简单介绍Python中的readline()方法的使用
May 24 Python
python字典的常用操作方法小结
May 16 Python
在Python的Flask中使用WTForms表单框架的基础教程
Jun 07 Python
Python可变参数用法实例分析
Apr 02 Python
python检测主机的连通性并记录到文件的实例
Jun 21 Python
Windows10下Tensorflow2.0 安装及环境配置教程(图文)
Nov 21 Python
tensorflow使用freeze_graph.py将ckpt转为pb文件的方法
Apr 22 Python
PyCharm2020.3.2安装超详细教程
Feb 08 Python
python迷宫问题深度优先遍历实例
Jun 20 Python
Pycharm连接远程服务器并远程调试的全过程
Jun 24 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
WINDOWS 2000下使用ISAPI方式安装PHP
2006/09/05 PHP
让CodeIgniter的ellipsize()支持中文截断的方法
2014/06/12 PHP
thinkPHP中验证码的简单使用方法
2015/12/26 PHP
php实现跨域提交form表单的方法【2种方法】
2016/10/17 PHP
Zend Framework数据库操作技巧总结
2017/02/18 PHP
Laravel 登录后清空COOKIE的操作方法
2019/10/14 PHP
[HTML/CSS/Javascript]WWTJS
2007/09/25 Javascript
js通过地址栏给action传值(中文乱码全是问号)
2013/05/02 Javascript
教你如何使用firebug调试功能了解javascript闭包和this
2015/03/04 Javascript
JS获取子窗口中返回的数据实现方法
2016/05/28 Javascript
微信小程序(应用号)简单实例应用及实例详解
2016/09/26 Javascript
JS中用三种方式实现导航菜单中的二级下拉菜单
2016/10/31 Javascript
AngularJs表单校验功能实例代码
2017/02/09 Javascript
JavaScript之promise_动力节点Java学院整理
2017/07/03 Javascript
vue组件实现文字居中对齐的方法
2017/08/23 Javascript
微信小程序开发之tabbar图标和颜色的实现
2018/10/17 Javascript
[01:09:23]KG vs TNC 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/16 DOTA
[35:55]完美世界DOTA2联赛PWL S3 Rebirth vs CPG 第一场 12.11
2020/12/13 DOTA
python实现的简单抽奖系统实例
2015/05/22 Python
深入解析Python设计模式编程中建造者模式的使用
2016/03/02 Python
python操作MySQL 模拟简单银行转账操作
2017/09/27 Python
python 3利用Dlib 19.7实现摄像头人脸检测特征点标定
2018/02/26 Python
使用PM2+nginx部署python项目的方法示例
2018/11/07 Python
Python基于scipy实现信号滤波功能
2019/05/08 Python
Python中利用LSTM模型进行时间序列预测分析的实现
2019/07/26 Python
CentOS7下安装python3.6.8的教程详解
2020/01/03 Python
Python 实现平台类游戏添加跳跃功能
2020/03/27 Python
使用css3 属性如何丰富图片样式(圆角 阴影 渐变)
2012/11/22 HTML / CSS
Book Depository亚太地区:一家领先的国际图书零售商
2019/05/05 全球购物
销售人员自我评价
2014/02/01 职场文书
航海技术专业毕业生求职信
2014/04/06 职场文书
霸气队列口号
2014/06/18 职场文书
2015年幼儿园国庆节活动总结
2015/07/30 职场文书
大学生村官驻村工作心得体会
2016/01/23 职场文书
CSS 使用 resize 实现图片拖拽切换预览功能(强大功能)
2021/08/23 HTML / CSS
7个关于Python的经典基础案例
2021/11/07 Python