2016-04-27 19 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

您可以定義列表,並追加您創建的列表中的所有字典對象。 e.g:

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對象:

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

你可以玩這個生成自己的JSON對象。 結帳json模塊

0

您的JSON輸出保持空白,因爲您的循環不附加到列表。

這是我會怎麼提取類別名稱:

​​