簡體   English   中英

Python + Selenium —無法訪問網頁上的元素

[英]Python + Selenium — Cannot access elements on a webpage

我正在嘗試訪問Selenium中的元素,但是沒有一種典型的方法有效。 到目前為止,我已經嘗試使用'find_elements_by_x'的每個變體都沒有成功。 我也花了大約一天的時間瀏覽各種論壇,但似乎沒有任何效果。 我最近在另一個成功的項目中使用了Selenium,但是對於該特定網站,相同的結構不起作用。 這是包含我要訪問的元素的HTML的代碼段:

<input type="text" name="username" id="username" placeholder="Username / 
Email" autocapitalize="off" autocorrect="off" required="" ng-
model="credentials.username" class="ng-pristine ng-invalid ng-invalid-
required">

顯而易見,這是用於登錄的用戶名輸入。下面是我到目前為止嘗試過的幾行,這些行都沒有用。

from selenium import webdriver


driver = webdriver.Chrome("chromedriver.exe filepath")
driver.get('url')

username = driver.find_element_by_xpath('//input[@id="username"]')

如果我使用Chrome中的控制台搜索XPath,則XPath會導航到有問題的元素。

我也嘗試過:

username = driver.find_element_by_name('username')

這也沒有用。

我對Selenium還是很陌生,並且對HTML完全沒有經驗,所以我不知道在通過Selenium查找元素時是否必須考慮到HTML中的復雜性。 任何幫助都表示贊賞。 這也是我第一次在這里發布,所以希望我沒有違反任何規則。

看起來輸入框需要花費幾秒鍾來加載。 嘗試在您的請求之前延遲一下:

driver.implicitly_wait(3)

如果這樣不起作用,請一次增加括號中的數字。 如果這樣可以解決問題,則可以改為顯式等待。

嘗試以下代碼:

from selenium import webdriver
from selenium.webdriver.support import ui
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By


options = Options()
options.add_argument("unlimited-storage")
driver = webdriver.Chrome(chrome_options=options)

driver.get("http://www.runescape.com/companion/comapp.ws")

iframe = ui.WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.TAG_NAME, "iframe")))

# Switch to the frame.
driver.switch_to.frame(iframe)

username = ui.WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "username")))

print(username)

# Switch to the main content.
driver.switch_to.default_content()

driver.quit()

希望對您有幫助!

按照您共享的HTMLWebElementAngular元素,因此您必須為該元素引入WebDriverWait ,如下所示:

  • CSS_SELECTOR

     username = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.ng-pristine.ng-invalid.ng-invalid-required#username"))) 
  • XPATH

     username = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='ng-pristine ng-invalid ng-invalid-required' and @id='username']"))) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM