我試圖讓網路驅動程式單擊站點
檢查網頁后,我發現網頁上的相應元素如下所示:

它在 iframe 內,有人建議我應該先切換到該 iframe 來定位元素,所以我將它合并到我的代碼中,但我經常NoSuchElementException出錯。我附上了我的代碼和下面的錯誤資訊供您參考。我不明白為什么盡管參考了 ID,但它無法找到按鈕元素,該 ID 在整個檔案中應該是唯一的。
編碼:
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Edge()
driver.get("https://www.random.org/")
driver.implicitly_wait(15)
driver.switch_to.frame(driver.find_element(By.TAG_NAME, "iframe"))
button = driver.find_element(By.CSS_SELECTOR, "input[id='hnbzsqjufzxezy-button']")
button.click()
錯誤資訊:

uj5u.com熱心網友回復:
確保頁面上沒有更多的 iframe。如果有幾個不僅一個這樣做:
iframes = driver.find_elements(By.CSS, 'iframe')
// try switching to each iframe:
driver.switch_to.frame(iframes[0])
driver.switch_to.frame(iframes[1])
您找不到該按鈕,因為它的名稱包含隨機字母。每次重繪 頁面時,您都可以看到名稱值會發生變化。所以,這樣做:
button = driver.findElement(By.CSS, 'input[type="button"][value="Generate"]')
button.click()
uj5u.com熱心網友回復:
您的代碼有幾個問題:
- 首先,您需要關閉 cookie 橫幅
- 按鈕的定位器錯誤。它的 id 是動態的。
- 您需要使用
WebDriverWait等待元素可點擊性。
以下代碼有效:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument("start-maximized")
webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service, options=options)
url = 'https://www.random.org/'
driver.get(url)
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[onclick*='all']"))).click()
wait.until(EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME, "iframe")))
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[id*='button']"))).click()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/512228.html
標籤:Python硒硒网络驱动程序css 选择器网络驱动程序等待
上一篇:型別不匹配:無法從List<Map<String,Object>>轉換為Map<String,Object>JAVA&SELENIUM
