Python基于pandas实现json格式转换成dataframe的方法
作者:zn505119020 发布时间:2021-08-23 23:09:01
标签:Python,pandas,json,dataframe
本文实例讲述了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
PS:这里再为大家推荐几款比较实用的json在线工具供大家参考使用:
在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat
在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson
json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat
在线json压缩/转义工具:
http://tools.jb51.net/code/json_yasuo_trans
更多Python相关内容感兴趣的读者可查看本站专题:《Python操作json技巧总结》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
来源:https://blog.csdn.net/zn505119020/article/details/78964111
0
投稿
猜你喜欢
- 现在很多朋友都不止一个账户,不止一个密码。忘记账户名、密码,或账户名、密码输入错误也就难免啦。每当这个时候,你是否和我一样会有小小的焦虑产生
- DateDiff 函数描述 返回两个日期之间的时间间隔。 语法 DateDiff(interval, date1, date2 [,firs
- 第一类工厂相当于mootools的Native方法,用于创建一些具有扩展能力的类,但这些类并没有继承能力,此类工厂也不能以某个类作为蓝本创建
- 本文实例讲述了php数组索引与键值操作技巧。分享给大家供大家参考。具体如下:<?php $array = array("a&
- android开发中在和服务器端接口对接时出现编码问题,从服务器端获取到的数据是 "\u8bbe\u59071ID-\u
- 本文实例分析了php5.4传引用时报错问题。分享给大家供大家参考,具体如下:php5.3系列版本以及以前版本,传引用没有什么问题,升级到ph
- 1.hashlib密码散列hashlib模块定义了一个API来访问不同的密码散列算法。要使用一个特定的散列算法,可以用适当的构造器函数或ne
- 转发时请保留此声明信息,这段声明不并会影响你的速度! @author:  
- 对python中的控制条件、循环和跳出详解代码缩进(代码块):python用缩进表示代码块,没有其他语言的大括号缩进是强制检查,整个代码缩进
- 我一直很难理解Javascript语言的继承机制。它没有"子类"和"父类"的概念,也没有"
- 九宫格是一种比较古老的设计,它最基本的表现其实就像是一个三行三列的表格。其实它最初是在window的c/s结构中用得比较多,比如我们经常看到
- 版本 0.9来自 http://onewww.net说明:当焦点不在表格内的input时,回车键复制最后一行,delete删除键最后一行选择
- 今天 大白 问了一个关于CSS权重的问题:关于选择器权重的问题 。class的权重是10 标签权重是 1 。比如说 p span{} 权重是
- PHP addAttribute() 函数实例给根元素和 body 元素添加一个属性:<?php $note=<<<
- 前言opencv中封装了一个专门用于求解cv::Mat均值的函数,即cv::mean(&cv::Mat),该函数会得到Mat中各个通
- 首先呢,需要有两个mysql服务器。如果做测试的话可以在同一台机器上装两个mysql服务程序,注意要两个运行程序的端口不能一样。我用的是一个
- 方法一:(by yangedie )这几天刚刚做了这个东西,有网友问到,所以分享一下。ie6、firefox2 通过,麻烦有ie7的网友测试
- 看下面的一组例子:alert(true.toString());alert(false.toString());alert(1.123.to
- 作者的blog:http://www.planabc.netz-index属性简介引用:z-index : auto | numberaut
- 1. 将Oracle 10g client安装包copy到本地才能安装:2. 双击setup 的到:3. 稍后进入安装界面:4. 选择下一步