我的 Python 中的 Selenium 自动化脚本遇到问题。直到昨天,一切都运转良好。然而,今天,脚本的表现并不如预期。
问题在于将 CPF(巴西身份证号码)输入表单字段的函数。尽管 CPF 值在代码中正确更新,但自动化仅将第一个值输入到字段中。当脚本尝试输入新的 CPF 时,无论传递的新值如何,都仅显示第一个值。
这是我的代码的相关部分:
def inserir_cpf(self, cpf):
print(f" Inside the Insert CPF function: {cpf}")
campo_cpf = WebDriverWait(self.driver, 10).until(
ec.presence_of_element_located((By.NAME, 'documentNumber'))
)
campo_cpf.clear() # Clears the field before inserting the new value
campo_cpf.send_keys(cpf)
self.simular()
def filtrar_cpf(self):
t = 0
while t < len(doc.dic_cpf):
print(t)
cpf = doc.list_cpf[t]
print('Selecting CPF')
print(cpf)
self.list_banco = ['BMP', 'QI', 'J17']
for i in self.list_banco:
print('Selecting Bank')
print(i)
bot.escolher_banco(i)
bot.inserir_cpf(cpf)
saldo_armazenado = bot.armazenar_saldo(cpf)
if saldo_armazenado:
print('Balance stored')
break
else:
print('Balance not found')
t += 1
我尝试过的 发送密钥之前清除字段:
campo_cpf.clear()
Ensuring the field is clickable:
campo_cpf = WebDriverWait(self.driver, 10).until(
ec.element_to_be_clickable((By.NAME, 'documentNumber'))
)
延迟逐字符插入值:
for char in cpf:
campo_cpf.send_keys(char)
time.sleep(0.1)
发送密钥之前确保该字段为空:
while campo_cpf.get_attribute('value') != '':
campo_cpf.clear()
这些尝试都没有解决问题。自动化仍然只将第一个值输入到字段中。
附加信息 相关字段由 By.NAME、“documentNumber”标识。 发送密钥后会调用函数 self.simular(),但即使注释掉该函数,问题仍然存在。 任何见解或建议将不胜感激。预先感谢您!
我找到了解决办法。我在函数内添加了一个 while 循环,将值插入到字段中。该字段使用退格键删除任何现有值,然后插入 CPF。稍后见。
代码中的解决方案:
def inserir_cpf(self, cpf):
print(f" Inside the Insert CPF function: {cpf}")
campo_cpf = WebDriverWait(self.driver, 10).until(
ec.presence_of_element_located((By.NAME, 'documentNumber'))
)
while cpf_field.get_attribute('value') != '':
cpf_field.send_keys(Keys.BACK_SPACE)
campo_cpf.clear() # Clears the field before inserting the new value
campo_cpf.send_keys(cpf)
self.simular()