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 相关文章推荐
简单介绍Python2.x版本中的cmp()方法的使用
May 20 Python
python 实现对文件夹内的文件排序编号
Apr 12 Python
python 执行文件时额外参数获取的实例
Dec 18 Python
selenium处理元素定位点击无效问题
Jun 12 Python
mac系统下Redis安装和使用步骤详解
Jul 09 Python
python实现网站微信登录的示例代码
Sep 18 Python
Python使用monkey.patch_all()解决协程阻塞问题
Apr 15 Python
python用TensorFlow做图像识别的实现
Apr 21 Python
解决keras加入lambda层时shape的问题
Jun 11 Python
使用Python爬取小姐姐图片(beautifulsoup法)
Feb 11 Python
Django项目在pycharm新建的步骤方法
Mar 02 Python
解决Python保存文件名太长OSError: [Errno 36] File name too long
May 11 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
destoon实现调用自增数字从1开始的方法
2014/08/21 PHP
PHP邮件发送类PHPMailer用法实例详解
2014/09/22 PHP
php中try catch捕获异常实例详解
2014/11/21 PHP
PHP中数据类型转换的三种方式
2015/04/02 PHP
php获取微信基础接口凭证Access_token
2018/08/23 PHP
thinkphp5.1框架模板赋值与变量输出示例
2020/05/25 PHP
js查找父节点的简单方法
2008/06/28 Javascript
JavaScript this调用规则说明
2010/03/08 Javascript
jquery表单验证使用插件formValidator
2012/11/10 Javascript
js中同步与异步处理的方法和区别总结
2013/12/25 Javascript
JS字符串拼接在ie中都报错的解决方法
2014/03/27 Javascript
JavaScript实现弹出子窗口并传值给父窗口
2014/12/18 Javascript
jquery中toggle函数交替使用问题
2015/06/22 Javascript
JS中多步骤多分步的StepJump组件实例详解
2016/04/01 Javascript
最丑的时钟效果!js canvas时钟制作方法
2016/08/15 Javascript
微信小程序中使用javascript 回调函数
2017/05/11 Javascript
vue 实现 tomato timer(蕃茄钟)实例讲解
2017/07/24 Javascript
js 获取json数组里面数组的长度实例
2017/10/31 Javascript
Vue弹出菜单功能的实现代码
2018/09/12 Javascript
vue 2.8.2版本配置刚进入时候的默认页面方法
2018/09/21 Javascript
小程序两种滚动公告栏的实现方法
2019/09/17 Javascript
[58:57]2018DOTA2亚洲邀请赛3月29日小组赛B组 Effect VS VGJ.T
2018/03/30 DOTA
python求众数问题实例
2014/09/26 Python
python实现批量图片格式转换
2020/06/16 Python
Python3使用PySynth制作音乐的方法
2019/09/09 Python
浅析PEP572: 海象运算符
2019/10/15 Python
在Pytorch中计算卷积方法的区别详解(conv2d的区别)
2020/01/03 Python
泰国的头号网上婴儿用品店:Motherhood.co.th
2019/04/09 全球购物
Opodo意大利:欧洲市场上领先的在线旅行社
2019/10/24 全球购物
杭州SQL浙江浙大网新恩普软件有限公司
2013/07/27 面试题
运动会通讯稿200字
2014/02/16 职场文书
通信工程专业求职信
2014/06/04 职场文书
学校安全教育月活动总结
2014/07/07 职场文书
2014年四风个人对照检查及整改措施
2014/10/28 职场文书
2015年幼儿园大班工作总结
2015/04/25 职场文书
结婚幸福感言
2015/08/01 职场文书