Selenium和Excel - 导入Excel数据和发送密钥

问题描述 投票:3回答:2

我正在开展一个项目,我需要将Excel工作表导入网站表单。我无法正确读取工作表中的数据并使用send_keys发送。

  • 首先,我在表单中创建了条目:

entries in the form

load_rows = 0
while load_rows < 101:
    add_element = driver.find_element_by_css_selector('.form-footer')
    add_element.click()
    load_rows = load_rows + 1
    driver.execute_script("window.scrollTo(0, 1000);") 
  • 然后,我从excel表中获取与网站上所需条目匹配的数据:

excel sheet

# Loading the Excel Info
filepath = "trusted_ips.xlsx"
wb = load_workbook(filepath)
ws = wb.active
max_row = sheet.max_row
max_column = sheet.max_column
print("Total columns : ", max_column)
print("Total rows : ", max_row)

似乎它将所有column A存储到name_elements.。因此,send_keys函数在移动到下一个字段之前发送所有column A

我希望它只将每个元素发送到一个字段,我认为列表可以解决这个问题。但我不太确定。

for name_elements in driver.find_elements_by_xpath ('//*[contains(@id, 
    "_name")]'):
    for row in ws['A2':'A100']:
        for cell in row:
            name_elements.send_keys(cell.value)
    print(name_elements)
python css selenium openpyxl
2个回答
1
投票

你可能想使用pandas或者将你的excel文件从openpyxl格式化为更易于管理的字典。

我已经完成了类似的工作,我需要从网站上删除excel文件的信息作为输入。

我的设置有点像以下

import pandas as pd

#load an excel file into a pandas dataframe
df = pd.read_excel("myfile.xlsx",
                    sheet_name=1, # pick the first sheet
                    index_col='client') # set the pandas index to be the column labeled 'client'

# .to_dict converts the dataframe to a dictionary with 'client' being the key, and the remaining rows being converted to dictionary with the column label as key and row as value
for client, record in df.to_dict(orient='records'):
    print(client) # use these print statements if what you're looping over is unfamiliar 
    print(record)
    driver.find_element('#client_input).send_keys(client)
    driver.find_element('#address_input').send_keys(record['address'])


0
投票

我能用以下方法解决这个问题 -

我创建了一个列表cells[]来存储值。然后使用变量name_elements来存储它们。设置counter=0

cells=[]
counter=0
name_elements = driver.find_elements_by_xpath ('//*[contains(@id, "_cidr")]')

第一个循环遍历excel表的A列,并将值存储在列表cells[]中。

for row in ws['C2':'C100']:
    for cell in row:
        cells.append(cell.value)

第二个循环取列表,因为每个值使用计数器循环执行发送密钥到下一个name_elements

for cell in cells:
    name_elements[counter].send_keys(cell)
    counter+=1
© www.soinside.com 2019 - 2024. All rights reserved.