【问题标题】:How to convert for loop generated data into Data Frame?如何将for循环生成的数据转换为数据框?
【发布时间】:2020-03-30 13:27:46
【问题描述】:

我使用 for 循环从网站中的表中提取数据 硒自动化网络驱动程序。如何将该数据转换为数据框 并导出为 csv 文件。我试图在 pandas 数据框中分配“值”,但它抛出错误。

from selenium import webdriver

url = "https://www.jambalakadi.info/status/"

driver = webdriver.Chrome(executable_path="chromedriver.exe")

driver.get(url)

row_count = len(driver.find_elements_by_xpath(" //*[@id='main_table_countries_today']/tbody[1]/tr "))
col_count = len(driver.find_elements_by_xpath(" //*[@id='main_table_countries_today']/tbody[1]/tr[1]/td "))

print('Number of row counts:', row_count)
print("Number of column counts:", col_count)


for r in range(2, row_count+1):
    for c in range(1, col_count+1):
        value = driver.find_element_by_xpath(" //*[@id='main_table_countries_today']/tbody[1]/tr["+str(r)+"]/td["+str(c)+"] ").text
        print(value, end=" ")

    print(" ")

当我运行 for 循环时,'value' 变量打印数据,但我 无法使用 pandas 创建数据框并将其导出为 CSV 文件。

我更新了代码格式是否正确?

my_data = []
for r in range(2, row_count+1):
    for c in range(1, col_count+1):
        value = driver.find_element_by_xpath(" //*[@id='main_table_countries_today']/tbody[1]/tr["+str(r)+"]/td["+str(c)+"] ").text
        print(value, end=" ")
        for line in value:
            my_data.append(line[0],line[1],line[2])
        pd.DataFrame.from_records(my_data, columns=column).to_csv('output.csv')

    print(" ")

【问题讨论】:

  • 你能分享你的网址吗?
  • 我没有提到网站网址,因为我在未经网站许可的情况下抓取数据。
  • 好的。那么你需要发布表格结构的html吗?

标签: python-3.x pandas selenium selenium-webdriver selenium-chromedriver


【解决方案1】:

这是使用pandas获取dataframe中的数据然后导入csv的代码。

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd
from bs4 import BeautifulSoup


driver=webdriver.Chrome(executable_path="chromedriver.exe")
driver.get("https://yourwebsitename.com")
WebDriverWait(driver,20).until(EC.visibility_of_element_located((By.CSS_SELECTOR,"table#main_table_countries_today")))
html=driver.page_source
soup=BeautifulSoup(driver.page_source,'html.parser')
table=soup.find('table',attrs={"id":"main_table_countries_today"})
df=pd.read_html(str(table))
print(df[0])
df[0].to_csv('output.csv',index=False)

更新

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import pandas as pd


driver=webdriver.Chrome(executable_path = "chromedriver.exe")
driver.get("https://yourwebsitename.com")
element=WebDriverWait(driver,20).until(EC.visibility_of_element_located((By.CSS_SELECTOR,"table#main_table_countries_today")))
table=driver.execute_script("return arguments[0].outerHTML;",element)
df=pd.read_html(str(table))
print(df[0])
df[0].to_csv('output.csv',index=False)

【讨论】:

  • 这段代码应该添加到我的代码中还是完全不同?当我收到错误消息时:“导致此警告的代码位于文件 /home/user/PycharmProjects/seleniumScrape/testing.py 的第 13 行。要消除此警告,请更改如下所示的代码:BeautifulSoup( YOUR_MARKUP}) "
  • @Jainmiah:你需要添加解析器以避免警告我已经添加了解析器。但是我发布了一个没有漂亮汤的解决方案。让我知道它是怎么回事?
  • 第一个工作得很好@KunduK 非常感谢你,实际上我是一个初学者,急切地想了解这个硒。怎样才能学得像上面的代码一样写出思路清晰?
  • 现在和昨天都有可用的选项卡,我可以使用 selenium 自动同时提取两者吗?
  • 获取昨天的值需要先通过selenium点击tab,然后才能获取到值。
【解决方案2】:

你需要使用pd.DataFrame.from_records()函数

用例:

import pandas as pd
#Reading the data
my_data = []
for line in my_database:
    #preprocess the line (say you get 3 columns date,customer,price)
    #say you use line.split(" "), now your line is actually an array of values (line = line.split(" ")
    my_data.append([line[0],line[1],line[2]]) #each index corresponds to date, customer and price respectively

pd.DataFrame.from_records(my_data, columns=['date','customer','price']).to_csv('output.csv')

【讨论】:

  • 如果有 100 行那么我应该手动提及 line[0],line[1],line[2] 或任何其他方式来修复它。
  • ... No. line[0] line[1] line[2] 代表您获得的值,即将读取的整行转换为值数组,并且 line[0 ] == array_of_values[0], line[1] == array_of_values[1] 等等。
  • 它说超出范围
猜你喜欢
  • 2020-11-27
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
  • 2021-07-31
  • 2021-08-21
  • 1970-01-01
  • 2016-03-17
  • 1970-01-01
相关资源
最近更新 更多