单击并打印需要Selenium Python的元素后,等待元素可见

2020-02-14 selenium

我想等待元素在单击后可见,然后打印所需的元素。但是除非我使用time.sleep,否则它就不会等待。我想用

WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'tbody')))

为了效率。

请帮忙。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
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(executable_path=r"C:\Users\Kim woo jae\PycharmProjects\100개 키워드\chromedriver.exe")

ky = '화장대','침대', '고기'
for k in ky:
    driver.get("http://whereispost.com/seller/")
    box = driver.find_element_by_xpath('//*[@id="keyword"]')
    box.clear()
    box.send_keys(k)
    box.submit()
    wait = WebDriverWait(driver, 20)
    b = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'tbody')))
    print(b.text)

这是我要使用的代码。但是,它不会等待元素可见。

driver = webdriver.Chrome(executable_path=r"C:\Users\Kim woo jae\PycharmProjects\100개 키워드\chromedriver.exe")

ky = '화장대','침대', '고기'

for k in ky:
    driver.get("http://whereispost.com/seller/")

    box = driver.find_element_by_xpath('//*[@id="keyword"]')
    box.clear()
    box.send_keys(k)
    box.submit()
  **time.sleep(3)**
    wait = WebDriverWait(driver, 20)
    b = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'tbody')))
    print(b.text)

如果我添加time.sleep(3),它可以正常工作。但是如果元素已经可见,我不想等待3秒。

Answers

tbody总是在那里;在您进行搜索之前,它是空的。

尝试等待tbody一些结果,例如:

wait = WebDriverWait(driver, 20)
b = wait.until(EC.visibility_of_element_located((By.XPATH, '//tbody//tr')))

Related