我正在使用Python,Selenium,openpyxl以便在线填写表格。为了填写表格,我从excel(.xlsx)上的特定单元格获取值。
A2
中,我获得该人的姓名,并将其插入在线表格中B2
中获取该人的年龄,并将其插入在线表单中我想创建一个循环,在该循环中,代码将再次从driver.get("https://XXXXXXXXXX")
开始,再次进入需要填写表单的页面,但是这次我要执行:
A3
,此人的姓名并将其插入在线表单中B3
,该人的年龄并将其插入在线表单中然后再次循环,从第4行插入数据,依此类推,直到excel上的行为空。
使用以下代码,我可以将数据插入在线表单:
from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException
import openpyxl
driver: WebDriver =
webdriver.Chrome("/Users/HHHHH/PycharmProjects/excel/driver/chromedriver")
driver.maximize_window()
excel_document = openpyxl.load_workbook(r"/Users/HHHHH/Desktop/testtesttest1.xlsx",
data_only=True)
sheet = excel_document["Sheet1"]
driver.get("https://XXXXXXXXXX")
#Insert in the form the Name of the person
prevsymbol = sheet["A2"].value
if prevsymbol == None:
pass
else:
try:
driver.find_element_by_id("name").send_keys(sheet["A2"].value)
except NoSuchElementException:
print("A2:(name) Not Found")
#Insert in the form the Age of the person
prevsymbol = sheet["B2"].value
if prevsymbol == None:
pass
else:
try:
driver.find_element_by_id("age").send_keys(sheet["B2"].value)
except NoSuchElementException:
print("B2:(Age) Not Found")
#click Save as a draft
driver.find_element_by_xpath("xpath_save_as_draft"). click()
您可以使用max_row
属性获取工作表中的行数。因此,代码变为:
from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.common.exceptions import NoSuchElementException
import openpyxl
driver: WebDriver =
webdriver.Chrome("/Users/HHHHH/PycharmProjects/excel/driver/chromedriver")
driver.maximize_window()
excel_document = openpyxl.load_workbook(r"/Users/HHHHH/Desktop/testtesttest1.xlsx",
data_only=True)
sheet = excel_document["Sheet1"]
for i in range(sheet.max_row):
driver.get("https://XXXXXXXXXX")
# Insert in the form the Name of the person
cell = "A" + str(i)
prevsymbol = sheet[cell].value
# Note that instead of doing the work at the else clause, you can negate the term
if prevsymbol is not None:
try:
# Note that we can use prevsymbol here, instead of referring to cell once again
driver.find_element_by_id("name").send_keys(prevsymbol)
except NoSuchElementException:
#
print(cell + ":(name) Not Found")
# Insert in the form the Age of the person
cell = "B" + str(i)
prevsymbol = sheet[cell].value
if prevsymbol is not None:
try:
driver.find_element_by_id("age").send_keys(prevsymbol)
except NoSuchElementException:
print(cell + ":(Age) Not Found")
# Click Save as a draft
driver.find_element_by_xpath("xpath_save_as_draft").click()