我的任务是修复办公室里运行在python上的数字标志环。原始脚本由于操作系统崩溃而丢失,我不得不重新创建它。我在修复使用selenium所能创建的内容时遇到了python的限制。
我编写了下面的脚本,它在循环中断之前的任意一段时间内运行,并且必须再次执行该脚本。
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
website = ["https://www.fireeye.com/cyber-map/threat-map.html",
"https://horizon.netscout.com/?sidebar=close",
"https://www.accuweather.com/en/us/minneapolis/55415/hourly-
weather-forecast/348794?=page",
"https://www.accuweather.com/en/us/minneapolis/55415/daily-
weather-forecast/348794?=page"
]
driver = webdriver.Chrome(r'/usr/bin/chromedriver')
driver.get(website[0])
driver.maximize_window()
driver.execute_script("window.open('about:blank', 'secondtab');")
driver.switch_to.window("secondtab")
driver.get(website[1])
driver.execute_script("window.open('about:blank', 'thirdtab');")
driver.switch_to.window("thirdtab")
driver.get(website[2])
driver.execute_script("window.scrollBy(0,250);")
driver.execute_script("window.open('about:blank', 'fourthtab');")
driver.switch_to.window("fourthtab")
driver.get(website[3])
driver.execute_script("window.scrollBy(0,100);")有人能告诉我为什么循环会中断吗?
循环是一个短暂的真实条件:
while True:
if "FireEye" in driver.title:
time.sleep(20)
driver.switch_to.window(driver.window_handles[1])
elif "Attack" in driver.title:
time.sleep(20)
driver.switch_to.window(driver.window_handles[2])
elif "Hourly" in driver.title:
time.sleep(10)
driver.switch_to.window(driver.window_handles[3])
elif "Daily" in driver.title:
time.sleep(10)
driver.switch_to.window(driver.window_handles[0])条件是检查每个网站的网页标签标题,因为每个都应该是真实的。
它以随机的间隔返回以下跟踪错误:
*driver.switch_to.window(driver.window_handles3)
IndexError:列出超出范围的索引*
我无法确定是什么导致索引不再起作用。
发布于 2022-11-28 23:53:40
在底部,python认为没有第四个窗口打开。首先,让我们加入一些错误处理,如下所示:
while True:
try:
if "FireEye" in driver.title:
time.sleep(20)
driver.switch_to.window(driver.window_handles[1])
elif "Attack" in driver.title:
time.sleep(20)
driver.switch_to.window(driver.window_handles[2])
elif "Hourly" in driver.title:
time.sleep(10)
driver.switch_to.window(driver.window_handles[3])
elif "Daily" in driver.title:
time.sleep(10)
driver.switch_to.window(driver.window_handles[0])
except:
foreach w in driver.window_handles:
print("{} is open!".format(w))这至少将继续循环,而不管错误,并告诉您,它认为哪些标签是打开的。
编辑:另外,作为一个注释,window_handles是没有排序的。因此,在一次迭代中可能出现的window_handles1可能在下一次迭代中成为window_handles3。
https://stackoverflow.com/questions/74604780
复制相似问题