from selenium import webdriver
import time
browser = webdriver.Chrome('C:/Users/acer/Desktop/chromedriver')
browser.get('website')
def user():
while True:
time.sleep(1)
try:
browser.find_element_by_id('q').send_keys('name') #Type in name
browser.find_element_by_tag_name('button').click() #Click "verify"
finally:
browser.find_element_by_tag_name('button').click() #When connection times out, click "try again"
user() #When connection times out again run "while loop" from the begining
我想当连接再次超时时从头开始,并进行永无休止的循环,直到连接成功。
最佳答案
看来你已经接近完美了。为了演示“当连接再次超时时从头开始并进行永无止境的循环,直到连接成功”,这里有一个小程序,它执行以下操作:
- 打开网址 https://www.google.com/
- 找出元素
By.NAME, "q"
- 清空字段
- 发送字符序列名称
- 尝试点击元素
find_element_by_tag_name('button')
- 失败并使用
继续
继续重试。 代码块:
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException, WebDriverException options = webdriver.ChromeOptions() options.add_argument("start-maximized") options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) browser = webdriver.Chrome(options=options, executable_path=r'C:\WebDrivers\chromedriver.exe') browser.get('https://www.google.com/') def user(): while True: print("Starting while loop") try: element = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.NAME, "q"))) element.clear() #clear the previous text element.send_keys('name') #Type in name browser.find_element_by_tag_name('button').click() except (WebDriverException, TimeoutException): print("Go to while loop from the begining") continue user()
控制台输出:
Starting while loop Go to while loop from the begining Starting while loop Go to while loop from the begining Starting while loop Go to while loop from the begining . . .
这个用例
您可以遵循类似的逻辑,您的有效代码块将是:
from selenium import webdriver
import time
browser = webdriver.Chrome('C:/Users/acer/Desktop/chromedriver')
browser.get('website')
def user():
while True:
time.sleep(1)
try:
browser.find_element_by_id('q').send_keys('name') #Type in name
browser.find_element_by_tag_name('button').click() #Click "verify"
except WebDriverException:
continue #When connection times out again run "while loop" from the begining
user()
关于python - 使用 Selenium 和 Python 从头开始使用 while 循环连接超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59811236/