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调用java的Webservice示例
Mar 10 Python
python自定义类并使用的方法
May 07 Python
python书籍信息爬虫实例
Mar 19 Python
Python实现带参数的用户验证功能装饰器示例
Dec 14 Python
一文了解Python并发编程的工程实现方法
May 31 Python
python中seaborn包常用图形使用详解
Nov 25 Python
python实现简单飞行棋
Feb 06 Python
在Keras中CNN联合LSTM进行分类实例
Jun 29 Python
Pycharm2020.1安装中文语言插件的详细教程(不需要汉化)
Aug 07 Python
Python使用requests模块爬取百度翻译
Aug 25 Python
python闭包与引用以及需要注意的陷阱
Sep 18 Python
如何用python清洗文件中的数据
Jun 18 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
很实用的一个完整email发送程序
2006/10/09 PHP
用PHP写的一个冒泡排序法的函数简单实例
2016/05/26 PHP
关于使用runtimeStyle属性问题讨论文章
2007/03/08 Javascript
js Canvas绘制圆形时钟效果
2017/02/17 Javascript
js的OOP继承实现(必看篇)
2017/02/18 Javascript
Node.js查找当前目录下文件夹实例代码
2017/03/07 Javascript
nodejs+websocket实时聊天系统改进版
2017/05/18 NodeJs
JS实现的加减乘除四则运算计算器示例
2017/08/09 Javascript
微信小程序实现流程进度的图样式功能
2018/01/16 Javascript
微信小程序数据统计和错误统计的实现方法
2019/06/26 Javascript
ES5 模拟 ES6 的 Symbol 实现私有成员功能示例
2020/05/06 Javascript
浅谈JavaScript中你可能不知道URL构造函数的属性
2020/07/13 Javascript
antd Form组件方法getFieldsValue获取自定义组件的值操作
2020/10/29 Javascript
Vant Weapp组件踩坑:picker的初始赋值解决
2020/11/12 Javascript
python Matplotlib画图之调整字体大小的示例
2017/11/20 Python
使用Python爬了4400条淘宝商品数据,竟发现了这些“潜规则”
2018/03/23 Python
对python 多线程中的守护线程与join的用法详解
2019/02/18 Python
python实现感知机线性分类模型示例代码
2019/06/02 Python
Python3内置模块pprint让打印比print更美观详解
2019/06/02 Python
python的re模块使用方法详解
2019/07/26 Python
Python字符串和正则表达式中的反斜杠('\')问题详解
2019/09/03 Python
python关闭占用端口方式
2019/12/17 Python
通过实例解析python描述符原理作用
2020/01/22 Python
selenium自动化测试入门实战
2020/12/21 Python
python如何发送带有附件、正文为HTML的邮件
2021/02/27 Python
The Athlete’s Foot新西兰:新西兰最大的运动鞋零售商
2019/12/23 全球购物
利用指针变量实现队列的入队操作
2012/04/07 面试题
中海讯通笔试题
2015/09/15 面试题
财务会计专业应届毕业生求职信
2013/10/18 职场文书
法语专业求职信
2014/07/20 职场文书
清明节寄语2015
2015/03/23 职场文书
2015年扫黄打非工作总结
2015/05/13 职场文书
新学期感想
2015/08/10 职场文书
2016教师暑期培训学习心得体会
2016/01/09 职场文书
Android开发之WECHAT微信小程序路由跳转的两种形式
2022/04/12 Java/Android
解决vue-router的beforeRouteUpdate不能触发
2022/04/14 Vue.js