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实现网站文件的全备份和差异备份
Nov 30 Python
python中日期和时间格式化输出的方法小结
Mar 19 Python
Python中输出ASCII大文字、艺术字、字符字小技巧
Apr 28 Python
栈和队列数据结构的基本概念及其相关的Python实现
Aug 24 Python
以一个投票程序的实例来讲解Python的Django框架使用
Feb 18 Python
python 网络编程常用代码段
Aug 28 Python
详解Python最长公共子串和最长公共子序列的实现
Jul 07 Python
Python利用heapq实现一个优先级队列的方法
Feb 03 Python
python爬虫爬取监控教务系统的思路详解
Jan 08 Python
python如何提升爬虫效率
Sep 27 Python
Python经纬度坐标转换为距离及角度的实现
Nov 01 Python
Django中template for如何使用方法
Jan 31 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
完美解决dedecms中的[html][/html]和[code][/code]问题
2007/03/20 PHP
php中存储用户ID和密码到mysql数据库的方法
2013/02/06 PHP
php中调用其他系统http接口的方法说明
2014/02/28 PHP
非常经典的PHP文件上传类分享
2016/05/15 PHP
解决PHP程序运行时:Fatal error: Maximum execution time of 30 seconds exceeded in的错误提示
2016/11/25 PHP
PHP实现对图片的反色处理功能【测试可用】
2018/02/01 PHP
nodejs 后缀名判断限制代码
2011/03/31 NodeJs
那些年,我还在学习jquery 学习笔记
2012/03/05 Javascript
JS增加行复制行删除行的实现代码
2013/11/09 Javascript
JavaScript统计字符串中每个字符出现次数完整实例
2016/01/28 Javascript
js replace(a,b)之替换字符串中所有指定字符的方法
2016/08/17 Javascript
轻松掌握JavaScript装饰者模式
2016/08/27 Javascript
js 实现一些跨浏览器的事件方法详解及实例
2016/10/27 Javascript
Vue.js用法详解
2017/11/13 Javascript
使用Bootstrap4 + Vue2实现分页查询的示例代码
2017/12/21 Javascript
vue配置请求本地json数据的方法
2018/04/11 Javascript
vue addRoutes实现动态权限路由菜单的示例
2018/05/15 Javascript
微信小程序-可移动菜单的实现过程详解
2019/06/24 Javascript
[47:08]OG vs INfamous 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/17 DOTA
对Python3中的print函数以及与python2的对比分析
2018/05/02 Python
Python 中Django验证码功能的实现代码
2019/06/20 Python
Python为何不支持switch语句原理详解
2020/10/21 Python
html5 css3 动态气泡按钮实例演示
2012/12/02 HTML / CSS
使用css如何制作时间ICON方法实践
2012/11/12 HTML / CSS
香港太阳眼镜网上商店:SmartBuyGlasses香港
2016/07/22 全球购物
加拿大知名的国际儿童品牌:Hatley
2016/11/09 全球购物
Myprotein俄罗斯官网:欧洲第一运动营养品牌
2019/05/05 全球购物
幼儿师范毕业生自荐信
2013/11/09 职场文书
教师评优事迹材料
2014/01/10 职场文书
战友聚会邀请函
2014/01/18 职场文书
销售助理岗位职责
2014/02/21 职场文书
大学新生入学教育方案
2014/05/16 职场文书
董事长助理岗位职责
2015/02/11 职场文书
2015年行政人事工作总结
2015/05/21 职场文书
初中体育教学随笔
2015/08/15 职场文书
在前女友婚礼上,用Python破解了现场的WIFI还把名称改成了
2021/05/28 Python