强制硒暂停并等待字段可用 [英] Force selenium to pause and wait for a field to be available

查看:67
本文介绍了强制硒暂停并等待字段可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的python脚本的代码段,该代码段正在读取excel文件,并将一行中的单元格分配给一个变量,然后将该变量用于在浏览器中键入字段.在大多数情况下,它都很棒.我想做的是在浏览器加载页面后设置某种循环以执行以下操作:

Below is a snippet of code from my python script that is reading an excel file and assigning cells in a row to a variable that is then used to be typed into a field in the browser. it works great ... for the most part. what i would like to do is setup some sort of loop after the browser loads the page to do the following:

通过一些ID查找元素.如果失败,请等待5秒钟,然后重试.如果成功,请继续执行脚本的其余部分.现在对我轻松一点,这是我第一次真正的尝试.我试过嵌套try/except语句,但是很快就变得混乱了.

find the element by some ID. if this fails, wait 5 seconds then try again. if it succeeds carry on with the rest of the script. now go easy on me, this is my first real attempt. i have tried to nest try/except statements but that got really messy fast.

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time
import xlrd

workbook = xlrd.open_workbook("my_excel_file.xlsx")
worksheet = workbook.sheet_by_name('Sheet1')
x = 0
for current_row in range(worksheet.nrows):
    try:
        cmt = worksheet.row(current_row)[2].value
        browser = webdriver.Firefox() # Get local session of firefox
        browser.get("http://www.somewebsite.com") # Load page
        time.sleep(5)
        #this timer is the issue, if the field takes 6 seconds to be ready, script fails
        comment = browser.find_element_by_id("slow_comment_box") # Find the comment box
        comment.send_keys(str(cmt) + Keys.RETURN)
        x += 1
    except:
        print ("Error on " + str(x))
        quit ()

是否可以将其设置为我上面所述的方式?我知道硒正在等待页面加载,但是文本框不是正常的,并且似乎有自己的加载,旋转轮.

is there a way to set this to behave the way i stated above? i know selenium waits for the page to load but the text box is not a normal one and appears to have its own loading, spinning wheel.

摘要和解决方案 答案如下.我愚蠢的东西有一些语法错误. 此页面也非常有用.

summary and solution the answer is below. my dumb stuff had some syntax errors. this page was extremely useful as well.

推荐答案

您要使用 WebDriverWait

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

element = WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.Id, 'id')))

这篇关于强制硒暂停并等待字段可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆