4 回答
TA贡献1811条经验 获得超4个赞
Instagram应用程序是通过React元素构建的。因此,在您开始搜索登录元素时调用 url 之后,您将面临NoSuchElementException
解决方案
要使用一组有效的凭据在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()
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
浏览器快照:
TA贡献1862条经验 获得超7个赞
观察打开 instagram 主页时,它会在登录表单上显示微调器片刻,然后显示字段。因此,您需要在脚本中管理同步。
在您的代码中使用显式等待,直到所需字段准备好进行交互。
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')
需要导入以下包
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
TA贡献1842条经验 获得超21个赞
试试下面的代码:
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()
导入后:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
TA贡献1811条经验 获得超5个赞
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')
添加回答
举报