【问题标题】:Populate a csv file with scraped data使用抓取的数据填充 csv 文件
【发布时间】:2020-05-24 09:18:56
【问题描述】:

我在这方面遇到了麻烦,我知道这是基本问题,因为我在周五问了一个类似的问题而被阻止了 2 天,但我真的很挣扎,所以希望能得到帮助。 如何编辑下面的代码以使用从机场站点提取的表格(即航班到达数据)填充我创建的 csv?

import requests
import csv, sys

from bs4 import BeautifulSoup

cookies = {
    'ApplicationGatewayAffinity': '1d2ad8ab214d1293a4e31bcd161589fa82a54a39bb7b3be80b503996092d4296',
    'ApplicationGatewayAffinityCORS': '1d2ad8ab214d1293a4e31bcd161589fa82a54a39bb7b3be80b503996092d4296',
}

headers = {
    'Connection': 'keep-alive',
    'Cache-Control': 'max-age=0',
    'Upgrade-Insecure-Requests': '1',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Sec-Fetch-Site': 'cross-site',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-User': '?1',
    'Sec-Fetch-Dest': 'document',
    'Referer': 'https://www.google.com/',
    'Accept-Language': 'en-GB,en;q=0.9,en-US;q=0.8,fr;q=0.7,nl;q=0.6',
}

response = requests.get('https://www.corkairport.com/arrivals-departures', headers=headers, cookies=cookies)

#print(response.content)
soup = BeautifulSoup(response.content, 'html.parser')

writer = csv.writer(sys.stdout)
writer.writerow([
    'Arriving From'
    'Airline',
    'Scheduled to arrive', 'Latest Update', 'Status'
    ])



with open('flight.csv','w') as f:
           [table] = soup.find_all("table")
           for row in table.find_all("tr"):
               writer.writerow(
               [td.string.strip() for td in row.find_all("td")]
           )
writer = csv.writer(f)

【问题讨论】:

  • 添加 2 个导入语句,您的代码就可以工作了——您面临的问题是什么?

标签: python function export-to-csv


【解决方案1】:

一个小错误,你需要在with block中有writer = csv.writer(f)

with open('flight.csv','w') as f:
    [table] = soup.find_all("table")
    writer = csv.writer(f)
    for row in table.find_all("tr"):
        writer.writerow(
        [td.string.strip() for td in row.find_all("td")]
    )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 2011-02-22
    • 2017-04-17
    相关资源
    最近更新 更多