我有以下Python代码:
import requests
import json
from bs4 import BeautifulSoup
url = requests.get('https://www.perfectimprints.com/custom-promos/20492/Beach-Balls.html')
source = BeautifulSoup(url.text, 'html.parser')
products = source.find_all('div', class_="product_wrapper")
def get_product_details(product):
product_name = product.find('div', class_="product_name").a.text
sku = product.find('div', class_="product_sku").text
product_link = product.find('div', class_="product_image_wrapper").find("a")["href"]
src = product.find('div', class_="product_image_wrapper").find('a').find("img")["src"]
return {
"title": product_name,
"link": product_link,
"sku": sku,
"src": src
}
all_products = [get_product_details(product) for product in products]
with open("products.json", "w") as write_file:
json.dump(all_products, write_file)
print("Success")
这段代码按照编写的方式完美运行。问题是我想要结构而不是
[
{
"title": "12\" Beach Ball",
"link": "/promos/PI-255-751/12-Beach-Ball.html?cid=20492",
"sku": " \n\t\t\t\t#PI-255-751\n\t\t\t",
"src": "https://12f598f3b6e7e912e4cd-a182d9508ed57781ad8837d0e4f7a945.ssl.cf5.rackcdn.com/thumb/751_group.jpg"
},
]
我希望它是:
{
"items": [
{
"title": "12\" Beach Ball",
"link": "/promos/PI-255-751/12-Beach-Ball.html?cid=20492",
"sku": " \n\t\t\t\t#PI-255-751\n\t\t\t",
"src": "https://12f598f3b6e7e912e4cd-a182d9508ed57781ad8837d0e4f7a945.ssl.cf5.rackcdn.com/thumb/751_group.jpg"
},
]
}
这是我在 Repl.it 中工作的链接,这样您就不必自己设置:https://repl.it/repls/AttractiveDimpledTheory
旁注:如果可能的话,希望能够删除 sku
中的所有 \n
和 \t
。
最佳答案
在这里,您将 all_products
列表直接转储为 JSON:
with open("products.json", "w") as write_file:
json.dump(all_products, write_file)
您想要的 JSON 只是在对象中包含该列表。类似的东西
with open("products.json", "w") as write_file:
json.dump({'items': all_products}, write_file)
应该做你想做的事。
一般来说,Python 数据结构与其生成的 JSON 之间存在 1:1 的关系。如果您构建正确的 Python 数据结构,您将获得正确的 JSON。在这里,我们使用 dict
(映射到 JSON 对象)来包装现有的 list
(映射到 JSON 数组)。
Side note: Would love to also be able to remove all of the
\n
and\t
in thesku
s if possible.
假设您还想删除空格,则可以使用 str.strip()
,默认情况下会去除空格:
return {
"title": product_name,
"link": product_link,
"sku": sku.strip(), # <-- here
"src": src
}
关于python - 在Python中将特定的JSON结构写入.json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52900086/