2016-04-27 12 views
1

ウェブサイトwww.theft-alerts.comをこすりました。今度はすべてのテキストを取得します。カテゴリごとにテキストをスクラップしてjsonファイルを作成する方法は?

connection = urllib2.urlopen('http://www.theft-alerts.com') 
soup = BeautifulSoup(connection.read().replace("<br>","\n"), "html.parser") 

theftalerts = [] 
for sp in soup.select("table div.itemspacingmodified"): 
    for wd in sp.select("div.itemindentmodified"): 
     text = wd.text 
     if not text.startswith("Images :"): 
      print(text) 

with open("theft-alerts.json", 'w') as outFile: 
    json.dump(theftalerts, outFile, indent=2) 

出力:

STOLEN : A LARGE TAYLORS OF LOUGHBOROUGH BELL 
Stolen from Bromyard on 7 August 2014 
Item : The bell has a diameter of 37 1/2" is approx 3' tall weighs just shy of half a ton and was made by Taylor's of Loughborough in 1902. It is stamped with the numbers 232 and 11. 

The bell had come from Co-operative Wholesale Society's Crumpsall Biscuit Works in Manchester. 
Any info to : PC 2361. Tel 0300 333 3000 
Messages : Send a message 
Crime Ref : 22EJ/50213D-14 

No of items stolen : 1 

Location : UK > Hereford & Worcs 
Category : Shop, Pub, Church, Telephone Boxes & Bygones 
ID : 84377 
User : 1 ; Antique/Reclamation/Salvage Trade ; (Administrator) 
Date Created : 11 Aug 2014 15:27:57 
Date Modified : 11 Aug 2014 15:37:21; 

どのようなカテゴリJSONファイルのテキストことができます。 JSONファイルが空になりました。

出力JSON:

[] 

答えて

0

あなたがリストを定義して、リストに作成するすべての辞書オブジェクトを追加することができます。例えば:あなたがあなた自身のJSONオブジェクトを生成するには、このと遊ぶことができる

[ 
    { 
    "category": "Shop", 
    "location": "UK" 
    }, 
    { 
    "category": "Shop", 
    "location": "UK" 
    } 
] 

:この後

import json 

theftalerts = []; 
atheftobject = {}; 
atheftobject['location'] = 'UK > Hereford & Worcs'; 
atheftobject['category'] = 'Shop, Pub, Church, Telephone Boxes & Bygones'; 
theftalerts.append(atheftobject); 

atheftobject['location'] = 'UK'; 
atheftobject['category'] = 'Shop'; 
theftalerts.append(atheftobject); 

with open("theft-alerts.json", 'w') as outFile: 
     print(json.dump(theftalerts, outFile, indent=2)) 

theft-alerts.jsonは、このJSONオブジェクトが含まれています実行します。 jsonモジュールをチェックアウト

0

ループがリストに追加されないため、JSON出力は空のままです。ここで

は、私は、カテゴリ名を抽出する方法をです:

​​
関連する問題