如何将网络爬虫数据保存为CSV文件?

3

我对Python、Selenium和BeautifulSoup都很陌生。我在网上看了很多教程,但是我感到很困惑。请帮助我。

基本上,这是我的Python代码:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from bs4 import BeautifulSoup as bs
    
    #import requests
    import time 
    #import csv
    
    passwordStr = '***'
    usernameStr='***'
    
    chrome_path = r'C:\Users\wana isa\geckodriver-v0.26.0-win64\geckodriver.exe'
    browser = webdriver.Firefox(executable_path=r'C:\Users\wana isa\geckodriver-v0.26.0-win64\geckodriver.exe')
    browser.get(('http://*********/'))
    
    wait = WebDriverWait(browser,10)
    
    
    # wait for transition then continue to fill items
    #time.sleep(2)
    password = wait.until(EC.presence_of_element_located((By.ID, 'txt_Password')))
    password.send_keys(passwordStr)
    username = wait.until(EC.presence_of_element_located((By.ID, 'txt_Username')))
    username.send_keys(usernameStr)
    
    signInButton = browser.find_element_by_id('button')
    signInButton.click()
    browser.get(('http://******'))
    
    
    MainTab=browser.find_element_by_name('mainli_waninfo').click()
    SubTab=browser.find_element_by_name('subli_bssinfo').click()
    browser.switch_to.frame(browser.find_element_by_id('frameContent'))
    
    html=browser.page_source
    soup=bs(html,'lxml')
    #print(soup.prettify())
    
#for Service Proversioning Status , This is the data that i scrape and need to be saved into csv
    spsList=['ONT  Registration Status','OLT Service Configuration Status','EMS Configuration Status','ACS Registration Status']
    sps_id=['td1_2','td2_2','td3_2','td4_2']
    for i in range(len(sps_id)):
        elemntValu = browser.find_element_by_id(sps_id[i]).text
        output= print(spsList[i] + " : "+ elemntValu)
        
    browser.close()

这是输出结果:

输入图像描述

非常感谢您的帮助。

1个回答

3

将以下导入语句添加到您的代码中:

import csv

将以下内容添加到您的代码中:

  with open('FileName.csv', 'w', newline='') as file:
      writer = csv.writer(file)
      for i in range(len(sps_id)):
            elemntValu = browser.find_element_by_id(sps_id[i]).text
            output= print(spsList[i] + " : "+ elemntValu)
            writer.writerow([spsList[i], elemntValu])
  f.close()
  browser.close()

1
我得到了这个错误 --> ValueError: 尝试在已关闭的文件上进行I/O操作 - Joojoo
@Joojoo编辑了,我添加了关闭文件的代码,请尝试并告诉我它是否有效。 - Asmoun
1
非常感谢,我已经明白了。但是我遇到了另一个问题。这个爬取的数据是动态的,每次运行时数值都会改变。如果已经保存的数据可以在每次运行时自动更改CSV文件中的内容,这是否可能? - Joojoo
@Joojoo,该文件实际上处于“w”模式,这意味着如果文件不存在,则创建文件并覆盖现有文件,因此您只需将此代码 with open('FileName.csv', 'w',newline='') 更改为 with open('FileName.csv', 'w') 即可。 - Asmoun
1
非常感谢!这真的帮了我很多。我不太习惯这种编码方式。这是我第一次爬取数据,也是我第一次使用Python。不过我还有一个问题,上面的数据是在列表中的。如果我想把它做成表格怎么办?我应该使用Pandas吗? - Joojoo
@Joojoo,欢迎你,看看这个Python表格,不需要用pandas。 - Asmoun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接