我收到这个奇怪的错误:
raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message:
Stacktrace:
RemoteError@chrome://remote/content/shared/RemoteError.sys.mjs:8:8
WebDriverError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:193:5
NoSuchElementError@chrome://remote/content/shared/webdriver/Errors.sys.mjs:511:5
dom.find/</<@chrome://remote/content/shared/DOM.sys.mjs:136:16
我使用 Firefox 作为驱动程序。
产生错误的代码非常简单。我想做的就是获取给定类的所有
div
,并为每个类获取每个 div 内 href
元素的 a
属性。当我在命令行中的 python 解释器内逐行运行代码时,它工作正常,但当我尝试在脚本的函数内运行它时,它会抛出错误。
这是代码:
def get_links(class_name):
profile_divs = self.browser.find_elements(By.CLASS_NAME, class_name)
links = []
for profile in profile_divs:
try:
# We get the a tag and append its href attribute to the links list
a_tag = WebDriverWait(profile, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'a')))
links.append(a_tag.get_attribute("href"))
except: # if no a tag is found in the div
continue
return(links)
引发错误的行是
a_tag = WebDriverWait(profile, 10).until(EC.presence_of_element_located((By.TAG_NAME, 'a')))
。但奇怪的是,当我单独运行每一行时它就起作用了。我认为这与等待时间有关,所以我添加了 WebDriverWait().until()。但尝试使用该功能时仍然不起作用。
如有任何帮助,我们将不胜感激
您可以尝试以下方法: 将 WebDriverWait 应用到整个驱动程序
a_tag = WebDriverWait(self.browser, 10).until(
EC.presence_of_element_located((By.TAG_NAME, 'a'))
希望有帮助!