Skip to main content
 首页 » 编程设计

python之如何将我的 Python 爬虫输出保存到 JSON 文件

2025年05月04日11kenshinobiy

我最近开始编码和学习 Python,目前正在开发网络爬虫。所以它目前只是打印出搜索结果。我想要的是它将数据保存到 JSON 文件中。

import requests 
import json 
from bs4 import BeautifulSoup 
 
url= "http://www.alternate.nl/html/product/listing.html?navId=11622&tk=7&lk=9419" 
r = requests.get(url)  
soup = BeautifulSoup(r.content) 
 
g_data = soup.find_all("div", {"class": "listRow"})  
for item in g_data:  
try:  
    print item.find_all("span", {"class": "name"})[0].text#1 
    print item.find_all("span", {"class": "additional"})[0].text#2 
    print item.find_all("span", {"class": "info"})[0].text#3 
    print item.find_all("span", {"class": "info"})[1].text#4 
    print item.find_all("span", {"class": "info"})[2].text#5 
    print item.find_all("span", {"class": "price right right10"})[0].text#6 
except:  
    pass      

这就是我想要它返回的:

{"product1":[{"1":"itemfindallresults1"},{"2":"itemfindallresults2"}]} etc 

那我该怎么做呢? 提前致谢。

请您参考如下方法:

一个简单的 JSON 用法是:

import json 
# open the file "filename" in write ("w") mode 
file = open("filename", "w") 
# just an example dictionary to be dumped into "filename" 
output = {"stuff": [1, 2, 3]} 
# dumps "output" encoded in the JSON format into "filename" 
json.dump(output, file) 
file.close() 

希望这对您有所帮助。