我正在尝试等待页面中的一些元素加载,然后再继续从页面输入/获取数据。一些阅读使我找到了这种代码:
#including imports in case they are influencing things
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver.get('example.com')
try:
element1_present = EC.presence_of_element_located((By.ID, 'id'))
WebDriverWait(driver, timeout).until(element1_present)
except TimeoutException:
print('Timed out waiting for page to load')
#Then get some data from example.com
Run Code Online (Sandbox Code Playgroud)
这工作得很好,但是,我想确定元素是否通过 CSS 选择器而不是 ID 存在。参考 Selenium 文档让我很困惑。它指出该presence_of_element_located方法应该将“定位器”作为参数,但是查看By文档,我没有看到(By.ID, 'id')有效的定位器如何(尽管很明显,它可以工作,但我不明白这一点),更具体地说,我不知道如何将其编码为 CSS 选择器定位器。
我曾尝试By.cssSelector,By.CSS和其他类似的术语来代替By.ID, 并移动括号,但我总是被退回:
AttributeError: type object 'By' has no …Run Code Online (Sandbox Code Playgroud)