将数据写入csv

时间:2017-06-29 11:43:31

标签: python csv web-scraping beautifulsoup

我正在从维基百科中抓取数据,到目前为止一直有效。我可以在终端上显示它,但是我不能按照我需要的方式将它写入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())

输出错误有两种方式。细胞是他们的正确位置,只写了一个城市,其他所有城市都缺失了。它看起来像这样:

enter image description here

但它应该看起来像这个+其他所有城市:

enter image description here

1 个答案:

答案 0 :(得分:0)

'...只写了一个城市......':您为每个城市拨打get_single_item_data。然后在此函数内部,在语句with open('staedte.csv', 'w', newline='', encoding='utf-8') as csvfile:中打开具有相同名称的输出文件,每次调用该函数时都会覆盖输出文件。

每个变量都写入一个新行:在语句writer.writerow({i: BeautifulSoup.get_text(items[1])})中,您将一个变量的值写入一行。您需要做的是在开始查找页面值之前创建值的字典。当您从页面累积值时,您可以按字段名称将它们推送到字典中。然后,在找到所有可用值后,请致电writer.writerow