2017-11-19 8 views
1

私はこのスクリプトを作成しましたが、データを保存するためのいくつかのオプションを試しましたが、私はコードを使いこなしています。抽出されたデータをCSVファイルまたはExcelファイルに保存するにはどうすればよいですか?ファイルを作成し、そこに壊れたデータを保存する方法は?

import requests 
from bs4 import BeautifulSoup 

base_url = "http://www.privredni-imenik.com/pretraga?abcd=&keyword=&cities_id=0&category_id=0&sub_category_id=0&page=1" 
current_page = 1 

while current_page < 200: 
    print(current_page) 
    url = base_url + str(current_page) 
    #current_page += 1 
    r = requests.get(url) 
    zute_soup = BeautifulSoup(r.text, 'html.parser') 
    firme = zute_soup.findAll('div', {'class': 'jobs-item'}) 

    for title in firme: 
     title1 = title.findAll('h6')[0].text 
     print(title1) 
     adresa = title.findAll('div', {'class': 'description'})[0].text 
     print(adresa) 
     kontakt = title.findAll('div', {'class': 'description'})[1].text 
     print(kontakt) 
     print('\n') 
     page_line = "{title1}\n{adresa}\n{kontakt}".format(
      title1=title1, 
      adresa=adresa, 
      kontakt=kontakt 
     ) 
    current_page += 1 

答えて

1

カンマで区切られた各ラインを印刷し、オペレーティング・システムの「>」は、ファイルへの書き込みに使用することですCSVを取得する簡単な方法。

import csv 
import requests 
from bs4 import BeautifulSoup 

base_url = "http://www.privredni-imenik.com/pretraga?abcd=&keyword=&cities_id=0&category_id=0&sub_category_id=0&page=1" 
current_page = 1 


with open('scrape_results.csv', 'w', newline='') as scrape_results: 
    csvwriter = csv.writer(scrape_results) 

    while current_page < 200: 
     url = base_url + str(current_page) 
     r = requests.get(url) 
     zute_soup = BeautifulSoup(r.text, 'html.parser') 
     firme = zute_soup.findAll('div', {'class': 'jobs-item'}) 

     for title in firme: 
      title1 = title.findAll('h6')[0].text 
      adresa = title.findAll('div', {'class': 'description'})[0].text 
      kontakt = title.findAll('div', {'class': 'description'})[1].text 
      csvwriter.writerow([current_page, title1, adresa, kontakt]) 

     current_page += 1 
+0

今、奇妙なことに、スクラップ、ケタックットは全くありません。私はタイトルとアドレサを得るだけです。しかし、それはCSVに保存されていると考えられています –

+0

OOps。私の間違いは、それが例外としてすべてを擦ったことが分かった!ありがとうございました! –

関連する問題