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


猜你喜欢
- Python 类/对象Python 是一种面向对象的编程语言。Python 中的几乎所有东西都是对象,拥有属性和方法。类(Class)类似对
- 一、交换变量x = 6y = 5x, y = y, xprint x>>> 5print y>>> 6二
- 一、安装相关的模块首先第一步的话我们需要安装相关的模块,通过pip命令来安装pip install gif另外由于gif模块之后会被当做是装
- 操作系统:Windows10 64bitPython版本:3.8.0下载地址:https://www.python.org/download
- Python自动的os库是和操作系统交互的库,常用的操作包括文件/目录操作,路径操作,环境变量操作和执行系统命令等。文件/目录操作获取当前目
- 使用perl连接mysql,这个网上有很多案例了,一般大家都是DBI下的DBD::MySQL这个模块进行.这里做一个mask弄一个TIPS:
- Python 字符串格式化使用 "字符 %格式1 %格式2 字符"%(变量1,变量2),%格式表示接受变量的类型。简单的
- 多版本并发控制Multiversion Concurrency Control大部分的MySQL的存储 引擎,比如InnoDB,Falcon
- 增大 SGA 已经缓冲看来对于性能的提升并不显著,加载时间只提升了 1.73%。下面我们增加 SGA 重做日志的大小: DB3: Log B
- 回顾面向对象编程让我们先用 30 秒钟来回顾一下 OOP 到底是什么。在面向对象编程语言中,可以定义 类,它们的用途是将相关的数据和行为捆绑
- 我们都知道在9i之前,要想获得建表和索引的语句是一件很麻烦的事。我们可以通过export with rows=no来得到,但它的输出因为格式
- 1.安装pm2 : npm install pm2 -gd这时在命令行下执行pm2命令可能找不到,需要执行如下命令1.创建软链接:ln -s
- PyCharm 是我用过的python编辑器中,比较顺手的一个。而且可以跨平台,在macos和windows下面都可以用,这点比较好。是py
- 一、DataFrame数据准备增、删、改、查的方法有很多很多种,这里只展示出常用的几种。参数inplace默认为False,只能在生成的新数
- 创建类Python 类使用 class 关键字来创建。简单的类的声明可以是关键字后紧跟类名:class ClassName(bases):&
- 1、选取最适用的字段属性MySQL可以很好的支持大数据量的存取,但是一般说来,数据库中的表越小,在它上面执行的查询也就会越快。因此,在创建表
- 死锁对于DBA或是数据库开发人员而言并不陌生,它的引发多种多样,一般而言,数据库应用的开发者在设计时都会有一定的考量进而尽量避免死锁的产生.
- 快捷键可以帮助我们有效提高效率,我们来看看网页设计软件FrontPage有哪些快捷键。相关文章:Dreamweaver快捷键大全、photo
- 一、生成器1、生成器定义在Python中,一边循环一边计算的机制,称为生成器:generator2、生成器存在的意义列表所有数据都在内存中,
- python格式化字符串有%和{}两种 字符串格式控制符.字符串输入数据格式类型(%格式操作符号)%%百分号标记#就是输出一个%%c字符及其