[英]Is there a way to convert list of string formatted dictionary to a dataframe in Python?
我正在練習如何使用 beautifulsoup 並且目前處於泡菜中,因為我無法將結果轉換為數據幀。 希望得到您的幫助。
在這個例子中,我想抓取的頁面可以使用以下方法獲得:
from bs4 import BeautifulSoup
import requests
import pandas as pd
page = requests.get("https://store.moncler.com/en-ca/women/autumn-winter/view-all-outerwear?tp=72010&ds_rl=1243188&gclid=EAIaIQobChMIpfDj9bjP5wIVlJOzCh0-9ghJEAAYASAAEgLuSfD_BwE&gclsrc=aw.ds", verify = False)
soup = BeautifulSoup(page.content, 'html.parser')
我已設法使用以下代碼隔離到產品部分
test_class = []
for section_tag in soup.find_all('section', class_='search__products__shelf search__products__shelf--moncler'):
for test in section_tag.find_all('article'):
test_class.append(test.get('data-ytos-track-product-data'))
其結果是一個字符串格式的字典列表,如下所示:
['{"product_position":0,"product_title":"TREPORT","product_brand":"MONCLER","product_category":"3074457345616676837/3074457345616676843","product_micro_category","product_micro_category","75g734micro_category","75g7373micro_category":"75g73734micro_category":"737300000000 ,"product_macro_category":"OUTERWEAR","product_macro_category_id":"3074457345616676837","product_color_id":"深藍色","product_color":"深藍色","product_price":0.0,"product_price.0,"5"3 :"0","product_discountedPrice_tf":"2126.05","product_id":"1890828705323513","product_variant_id":"1890828705323514","list":"searchresult","product_"product_quantity": "product_cod8":null,"product_cod10":null,"product_legacy_macro_id":"1012","product_legacy_micro_id":"1446","product_is_in_stock":true,"is_rsi_product":false,"rsi_product_tracking_url":""}' {"product_position":1,"product_title":"RIMAC","product_brand":"MONCLER","product_category":"3074457345616676837/3074457345616676854","product_micro_category":","product_micro_category" category_id":"3074457345616676854","product_macro_category":"OUTERWEAR","product_macro_category_id":"3074457345616676837","product_color_id":"深藍色","product_price","countdark_price blue":"countDark_price :2340.0,"product_price_tf":"0","product_discountedPrice_tf":"1966.39","product_id":"5549023491788128","product_variant_id":"55490234917881","product_result", product_coupon":"","product_cod8":null,"product_cod10":null,"product_legacy_macro_id":"1012","product_legacy_micro_id":"4715","product_is_in_stock":true,"is_rsi_product":false,"rsi_product_track ""}',
我的問題是如何將結果從這樣的字符串格式字典列表轉換為熊貓數據框?
我嘗試使用下面的代碼開始
import ast
ast.literal_eval(test_class[1])
但無濟於事(它給了我下面的錯誤代碼)。
ValueError:格式錯誤的節點或字符串:<_ast.Name object at 0x000001985A976748>
最終結果應將字典的每個鍵存儲到 Dataframe 中的列中(即“product_position”、“product_title”、“product_brand”等)
任何幫助/指導將不勝感激。
謝謝。
看起來問題真的是關於如何解析字符串,而不是如何用熊貓做某事。
您擁有的列表似乎只包含有效的 json 字符串。 您可以使用標准庫中的json.loads()
將它們轉換為 python dict。 當然,如果某些字符串格式錯誤,那就是另一回事了,您將不得不谷歌如何解析格式錯誤的 jsons。
在獲得 python dicts 列表后,將它們轉換為 DataFrame 是微不足道的。
您可以使用json.loads
,然后使用獲得的字典列表實例化pandas.DataFrame
:
d = [json.loads(e) for e in data]
df = pd.DataFrame(d)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.