Selenium命令崩溃



我已经为数据检索编写了一个简单的爬网程序,但有时特定的命令会因其他元素而崩溃。例如以下命令:

driver.find_element_by_xpath("//a[@class='abcs__123 js-tabs ']").click()

退货:

selenium.common.exceptions.ElementClickInterceptedException: Message: Element <a class="abcs__123 js-tabs "> is not clickable at point (549,38) because another element <div class="header__container"> obscures it

如何解决此问题?现在我使用以下技巧:

time.sleep(8)

但它以固定的速率延迟了我的程序,而不能保证上述错误的避免。

有几种情况会发生这种情况,所以我不知道在特定情况下到底是什么原因导致了问题
在大多数情况下,使用JavaScript单击元素或使用Actions移动到元素,然后单击它会有所帮助
因此,请尝试以下任何一种:

element = driver.find_element_by_xpath("//a[@class='abcs__123 js-tabs ']")
driver.execute_script("arguments[0].click();", element)

element = driver.find_element_by_xpath("//a[@class='abcs__123 js-tabs ']")
webdriver.ActionChains(driver).move_to_element(element ).click(element ).perform()

当你想找到元素时,它可能不会加载它,但这个问题有几个原因。如果你的问题是关于加载元素的时间,请测试这个:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
driver = webdriver.Chrome() #or firefox
driver.get("url")
delay = 10 #sec
try:
element = WebDriverWait(driver, delay).until(EC.presence_of_element_located((By.XPATH, '//a[@class='abcs__123 js-tabs ']')))
print ("Element loaded")
except TimeoutException:
print ("Loading too much time")

最新更新