【问题标题】:Exporting data scraped with Selenium to a csv file将使用 Selenium 抓取的数据导出到 csv 文件
【发布时间】:2017-06-30 01:57:26
【问题描述】:

我正在尝试获取 https://icostats.com/ 的首页中的数据并将其导出到 .csv 文件。到目前为止,这是我的代码:

import csv
from selenium import webdriver

def get_elements_by_xpath(driver, xpath):
    return [entry.text for entry in driver.find_elements_by_xpath(xpath)]

url = ("https://icostats.com")
driver = webdriver.Firefox(executable_path=r'C:\Users\alph1\Scrapers\geckodriver.exe')
driver.get(url)

search_entries = [
    ("NAME", "//div[@class='tdName-0-73']"),
    ("DATE", "//div[@class='tdDate-0-74']"),
    ("CUR PRICE", "//div[@class='tdPrice-0-72'][1]"),
    ("ICO PRICE", "//div[@class='tdPrice-0-72'][0]"),
    ("24H ROI", "//div[@class='tdPrimary-0-75']")]

with open('textfile.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output)

    # Write header
    csv_output.writerow([name for name, xpath in search_entries])
    entries = []

    for name, xpath in search_entries:
        entries.append(get_elements_by_xpath(driver, xpath))

    csv_output.writerows(zip(*entries))

get_elements_by_xpath()

这是我得到的例外。

文件“C:/Users/alph1/PycharmProjects/PyQtPS/ICO2CSV.py”,第 28 行,在 csv_output.writerow([name for name,xpath in search_entries]) TypeError:需要一个类似字节的对象,而不是'str'

我有一种感觉,我最终不应该调用这样的方法,但不知道我该怎么做。

【问题讨论】:

标签: python selenium web-scraping


【解决方案1】:

我相信这是因为您已将文件作为二进制文件 (open('textfile.csv', 'wb') 打开。这意味着来自它的所有数据都将以二进制形式读取,作为字节。

要解决这个问题,只需执行 open('textfile.csv', 'w') 即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    相关资源
    最近更新 更多