【问题标题】:Write data into csv将数据写入csv
【发布时间】:2017-12-03 02:24:39
【问题描述】:

我正在从 Wikipedia 抓取数据,并且到目前为止它可以正常工作。我可以在终端上显示它,但我不能按照我需要的方式将它写入 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 个方面不正确。牢房是他们正确的地方,只写了一个城市,其他的都不见了。它看起来像这样:

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

【问题讨论】:

  • 输出有什么问题?
  • 我做了截图。您可以使用代码轻松测试它,它适用于 Python 3.6。

标签: python csv web-scraping beautifulsoup


【解决方案1】:

'...只写了一个城市...':您为每个城市调用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-27
    • 2021-05-17
    • 2018-11-11
    • 2019-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多