我正在嘗試使用Selenium接受 cookie ,但找不到接受按鈕。我對Selenium不熟悉,也不知道如何除錯。例如,如果我嘗試接受來自webrankinfo.com的 cookie 。
這是我的代碼:
driver = webdriver.Chrome("chromedriver")
driver.get("https://www.webrankinfo.com")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[normalize-space()='Tout accepter et continuer']"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[contains(., 'Tout accepter et continuer')]"))).click()
無論選擇何種選項(Xpath 或 CSS),都找不到該按鈕。解決辦法是什么?
此外,是否有任何選項可以直接在我的 Web 瀏覽器(如 Chrome 或 Firefox )上除錯 Xpath ?
uj5u.com熱心網友回復:
我在該網頁上沒有看到任何“接受 cookie”按鈕,因此我無法為其提供定位器。
關于使用 Firefox 的 Chrome 除錯定位器:
您可以在瀏覽器上按下F12,它將打開開發者工具。
然后在那里選擇Elements選項卡。
然后,您可以在那里找到帶有左上角箭頭的任何元素。
它將顯示所選元素的所有屬性。
Control F在該視圖上將允許您使用 XPath 或 CSS 選擇器搜索該頁面上的元素。
另請參閱此處或有關使用開發人員工具定位 Web 元素的任何其他資源。
uj5u.com熱心網友回復:
作為先知,我沒有出現 cookie 警報,所以我無法幫助您找到按鈕。雖然,我可以幫助您嘗試使 cookie 警報根本不出現。某些網站只需要特定瀏覽器或瀏覽器版本的 cookie。這樣,更改 WebDriver 的用戶代理可能會導致警報消失。您的代碼將是這樣的:
options = webdriver.ChromeOptions()
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
options.add_argument('user-agent={0}'.format(user_agent))
driver = webdriver.Chrome("chromedriver")
driver.get("https://www.webrankinfo.com")
那個用戶代理只是一個例子,也許它不會作業,但其他人會。您可以在此處找到舊版 Chrome 。
也可能發生的是該網站正在檢測自動化工具。這將解釋為什么 cookie 警報沒有顯示給我們。為了防止檢測,您必須向 WebDriver 添加一些選項引數:
options = webdriver.ChromeOptions()
options.add_argument('--no-sandbox')
options.add_argument('--allow-running-insecure-content')
options.add_argument('--ignore-certificate-errors')
options.add_argument('-allow-insecure-localhost')
options.add_argument('--remote-debugging-port=9222')
options.add_argument('--disable-gpu')
options.add_argument('--start-maximized')
options.add_experimental_option("useAutomationExtension", False)
options.add_experimental_option("excludeSwitches",["enable-automation"])
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
options.add_argument('user-agent={0}'.format(user_agent))
driver = webdriver.Chrome("chromedriver")
driver.get("https://www.webrankinfo.com")
其中一些論點可能毫無用處。因此,您可以一一測驗它們,并只讓您的代碼使用有用的代碼。
uj5u.com熱心網友回復:
正如我所看到的 cookie 資訊的加載時間比它自己的頁面要晚,所以在實際點擊接受按鈕之前使用等待。
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.elementClickable( insert your element here ));
然后是 xpath 的另一個建議,如果你想通過其中的文本找到一個跨度
//span[text()='Accept all']
我認為您第二次嘗試的正確形式是
//span[text()[contains(.,'Accept all')]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/451814.html
上一篇:Selenium驅動程式未關閉時出現InvalidSessionIdException
下一篇:縮短硒線選項
