Selenium和Excel - 导入Excel数据并发送按键

3
我正在处理一个项目,在这个项目中我需要将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)

看起来它正在将 列A 的所有内容存储到 name_elements 中。因此,在移动到下一个字段之前,send_keys 函数会发送 列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)
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'])


这里实际上不需要使用pandas:工作表中的行已经与表单中的字段对应,因此仅基于第一行的简单辅助字典就足够了。 - Charlie Clark

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

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