2017-06-29 26 views
1

私はWikipediaからデータをクロールしています。これまでのところ動作しています。私は端末に表示することができますが、私はそれをcsvファイルに必要な方法で書くことはできません: -/ コードはかなり長いですが、とにかくここに貼り付けて、誰かが私を助けることを願っています。csvにデータを書き込む

import csv 
import requests 
from bs4 import BeautifulSoup 


def spider(): 
    url = 'https://de.wikipedia.org/wiki/Liste_der_Gro%C3%9F-_und_Mittelst%C3%A4dte_in_Deutschland' 
    code = requests.get(url).text # Read source code and make unicode 
    soup = BeautifulSoup(code, "lxml") # create BS object 

    table = soup.find(text="Rang").find_parent("table") 
    for row in table.find_all("tr")[1:]: 
     partial_url = row.find_all('a')[0].attrs['href'] 
     full_url = "https://de.wikipedia.org" + partial_url 
     get_single_item_data(full_url)   # goes into the individual sites 


def get_single_item_data(item_url): 
    page = requests.get(item_url).text # Read source code & format with .text to unicode 
    soup = BeautifulSoup(page, "lxml") # create BS object 
    def getInfoBoxBasisDaten(s): 
     return str(s) == 'Basisdaten' and s.parent.name == 'th' 
    basisdaten = soup.find_all(string=getInfoBoxBasisDaten)[0] 

    basisdaten_list = ['Bundesland', 'Regierungsbezirk:', 'Höhe:', 'Fläche:', 'Einwohner:', 'Bevölkerungsdichte:', 
         'Postleitzahl', 'Vorwahl:', 'Kfz-Kennzeichen:', 'Gemeindeschlüssel:', 'Stadtgliederung:', 
         'Adresse', 'Anschrift', 'Webpräsenz:', 'Website:', 'Bürgermeister', 'Bürgermeisterin', 
         'Oberbürgermeister', 'Oberbürgermeisterin'] 

    with open('staedte.csv', 'w', newline='', encoding='utf-8') as csvfile: 
     fieldnames = ['Bundesland', 'Regierungsbezirk:', 'Höhe:', 'Fläche:', 'Einwohner:', 'Bevölkerungsdichte:', 
         'Postleitzahl', 'Vorwahl:', 'Kfz-Kennzeichen:', 'Gemeindeschlüssel:', 'Stadtgliederung:', 
         'Adresse', 'Anschrift', 'Webpräsenz:', 'Website:', 'Bürgermeister', 'Bürgermeisterin', 
         'Oberbürgermeister', 'Oberbürgermeisterin'] 
     writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=';', quotechar='|', quoting=csv.QUOTE_MINIMAL, extrasaction='ignore') 
     writer.writeheader() 

     for i in basisdaten_list: 
      wanted = i 
      current = basisdaten.parent.parent.nextSibling 
      while True: 
       if not current.name: 
        current = current.nextSibling 
        continue 
       if wanted in current.text: 
        items = current.findAll('td') 
        print(BeautifulSoup.get_text(items[0])) 
        print(BeautifulSoup.get_text(items[1])) 
        writer.writerow({i: BeautifulSoup.get_text(items[1])}) 

       if '<th ' in str(current): break 
       current = current.nextSibling 


print(spider()) 

出力には2通りの方法があります。セルは正しい場所にあり、1つの都市だけが書かれ​​、他はすべて失われています。 '...のみ1つの都市が書かれている...'

enter image description here

+0

出力にはどのような問題がありますか? –

+0

私はスクリーンショットを作成しました。 Python 3.6で動作するコードで簡単にテストできます。 – saitam

答えて

0

:それは次のようになります。

enter image description here

しかし、それは、この+その中のすべての他の都市のようになります。:都市ごとにget_single_item_dataに電話してください。この関数の中で、同じ名前の出力ファイルを開くと、関数を呼び出すたびに出力ファイルを上書きする文with open('staedte.csv', 'w', newline='', encoding='utf-8') as csvfile:が表示されます。

各変数は新しい行に書き込まれますwriter.writerow({i: BeautifulSoup.get_text(items[1])})ステートメントでは、1つの変数の値を1つの行に書き込みます。代わりに行う必要があるのは、ページ値の検索を開始する前に値の辞書を作成することです。あなたがページから値を累積すると、それらをフィールド名で辞書に移動します。利用可能な値がすべて見つかったらwriter.writerowに電話してください。

関連する問題