4 回答

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超4個(gè)贊
Instagram應(yīng)用程序是通過(guò)React元素構(gòu)建的。因此,在您開(kāi)始搜索登錄元素時(shí)調(diào)用 url 之后,您將面臨NoSuchElementException
解決方案
要使用一組有效的憑據(jù)在Instagram中登錄,您需要引入WebDriverWait并且element_to_be_clickable()
您可以使用以下 定位器策略:
使用XPATH:
driver.get("https://www.instagram.com/")
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='username']"))).send_keys("username")
driver.find_element_by_xpath("//input[@name='password']").send_keys("password")
driver.find_element_by_xpath("//button/div[text()='Log In']").click()
注意:您必須添加以下導(dǎo)入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
瀏覽器快照:

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超7個(gè)贊
觀(guān)察打開(kāi) instagram 主頁(yè)時(shí),它會(huì)在登錄表單上顯示微調(diào)器片刻,然后顯示字段。因此,您需要在腳本中管理同步。
在您的代碼中使用顯式等待,直到所需字段準(zhǔn)備好進(jìn)行交互。
username = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//input[@name='username']")))
username.send_keys('username')
password = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//input[@name='password']")))
password.send_keys('pw')
需要導(dǎo)入以下包
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超22個(gè)贊
試試下面的代碼:
driver = webdriver.Chrome()
driver.get('https://www.instagram.com/')
txt_user = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.NAME, 'username')))
txt_user.send_keys('yourUserName')
txt_pwd = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.NAME, 'password')))
txt_pwd.send_keys('yourPassword')
btn_submit = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'button[type="submit"]')))
btn_submit.click()
導(dǎo)入后:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超5個(gè)贊
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get('https://www.instagram.com/')
element = WebDriverWait(driver, 2).until(
EC.presence_of_element_located((By.ID, "//input[@name=\"username\"]"))
)
element.sendkeys('user')
添加回答
舉報(bào)