使用硒选择输入字段时出错

问题描述 投票:0回答:2

在下面的代码中,我试图使用Selenium和python登录Instagram帐户。

我使用了不同的方法来定位字段并用适当的数据填充它们,但是在所有情况下,它都无法定位元素。

这些是我尝试填写的字段:Username

<input aria-label="Phone number, username, or email" aria-required="true" autocapitalize="off" autocorrect="off" maxlength="75" name="username" type="text" class="_2hvTZ pexuQ zyHYP" value="">

密码:

<input aria-label="Password" aria-required="true" autocapitalize="off" autocorrect="off" name="password" type="password" class="_2hvTZ pexuQ zyHYP" value="">

这是我的代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

class InstagramBot():
    def __init__(self,username, password):
        self.browser = webdriver.Chrome()
        self.username = username
        self.password = password
        time.sleep(4)

    def login(self):
        self.browser.get('https://www.instagram.com/accounts/login')

        usernameInput = self.browser.find_element_by_name('username')
        passwordInput = self.browser.find_element_by_name('password')
        usernameInput.send_keys(self.username)
        passwordInput.send_keys(self.password)
        self.browser.send_keys(Keys.ENTER)
        time.sleep(2)


bot = InstagramBot('MY_USERNAME', 'MY_PASSWORD')
bot.login()
python selenium authentication xpath instagram
2个回答
1
投票

[可能是在浏览器获取方法之后立即搜索元素时,甚至在页面加载之前就搜索了元素,最好的方法不是休眠而是等待

尝试:

from selenium import webdriver                                                  
from selenium.webdriver.common.keys import Keys                                 
from selenium.webdriver.common.by import By                                     
from selenium.webdriver.support.ui import WebDriverWait                         
from selenium.webdriver.support import expected_conditions as EC                
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.chrome.options import Options
import time
import sys

### your browser definition etc
wait  = WebDriverWait(browser, 4)
# now your browser will wait for 4 seconds and will throw an error if he didnt finds the element
try:
    wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="STRUCTURED_EDITOR.FLIGHT_DATA_AREA.GENERAL_DATA_ENTRY.AIRCRAFT_ID_FIELD"]')))
except TimeoutException:
    print("time error")
    browser.quit()

element_drop_down = browser.find_element_by_xpath('//*[@id="STRUCTURED_EDITOR.FLIGHT_DATA_AREA.GENERAL_DATA_ENTRY.AIRCRAFT_ID_FIELD"]')
element_drop_down.send_keys("{}".format(my_var))

还检查是否有多个帧,如果元素在辅助帧内,则需要切换帧


0
投票

您的脚本没有任何问题,只需等待页面加载

time.sleep(4)之后移动self.browser.get('https://www.instagram.com/accounts/login')

def login(self):
    self.browser.get('https://www.instagram.com/accounts/login')
    time.sleep(4)
    usernameInput = self.browser.find_element_by_name('username')
    passwordInput = self.browser.find_element_by_name('password')
    usernameInput.send_keys(self.username)
    passwordInput.send_keys(self.password)
© www.soinside.com 2019 - 2024. All rights reserved.