将使用Selenium抓取的数据导出到csv文件

时间:2017-06-30 01:57:26

标签: python selenium web-scraping

我尝试将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'

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

1 个答案:

答案 0 :(得分:0)

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

要解决此问题,只需改为open('textfile.csv', 'w')即可。

相关问题