2014-11-20 6 views
2

저는 최근 파이썬을 코딩하고 배우기 시작했습니다. 현재는 웹 크롤러에서 작업하고 있습니다. 그래서 현재는 검색 결과를 인쇄하고 있습니다. 내가 원한 것은 데이터를 JSON 파일에 저장한다는 것이다.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 

그래서 내가 그걸 어떻게 할 수

? 미리 감사드립니다.

+0

먼저 'my_data = { "product1": [...]}'을 만들고, 다음에'json.dump (my_data, ...)'를 사용하십시오. – furas

답변

1

간단한 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() 

희망이 도움이됩니다.

0

요구 사항을 충족하는 간단한 프로그램입니다.

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) 

product = Product() 

g_data = soup.find_all("div", {"class": "listRow"}) 
for item in g_data: 
try: 
    product.set_<field_name>(item.find_all("span", {"class": "name"})[0].text) 
    product.set_<field_name>("span", {"class": "additional"})[0].text 
    product.set_<field_name>("span", {"class": "info"})[0].text 
    product.set_<field_name>("span", {"class": "info"})[1].text 
    product.set_<field_name>("span", {"class": "info"})[2].text 
    product.set_<field_name>("span", {"class": "price right right10"})[0].text 
except: 
    pass 

import json 
file = open("filename", "w") 
output = {"product1": product} 
json.dump(output, file) 
file.close() 
관련 문제