简体   繁体   English

使用 selenium 和 webdriver (chrome) python OSX 在 Instagram 中填写登录表单

[英]Filling in login forms in Instagram using selenium and webdriver (chrome) python OSX

I want to log in to instagram using selenium, but I can't seem to enter values into the fields.我想使用 selenium 登录 instagram,但我似乎无法在字段中输入值。

Here's my script:这是我的脚本:

#go to this address
browser.get('https://www.instagram.com')

#sleep for 1 seconds
sleep(1)

#find the 'login' button on homepage
login_elem = browser.find_element_by_xpath(
'//*[@id="react-root"]/section/main/article/div[2]/div[2]/p/a')

#navigate to login page
login_elem.click()

Having trouble from here onwards:从这里开始遇到麻烦:

#locate the username field within the form
unform = browser.find_element_by_xpath(
'//*[@id="f3b8e6724a27994"]')

#clear the field
textunform.clear()

#enter 'test' into field
unform.send_keys('test')

There is a trick in this, instead of searching for the Button (Log In) there is a better way to log in without it.这有一个技巧,而不是搜索按钮(登录),有一种更好的方法可以不用它来登录。 how?如何? let's see:让我们来看看:

Import the packages you need:导入你需要的包:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
#Select the driver, In our case we will use Chrome.
chromedriver_path = 'chromedriver.exe' # Change this to your own chromedriver path!
webdriver = webdriver.Chrome(executable_path=chromedriver_path)
sleep(2)
webdriver.get('https://www.instagram.com/accounts/login/?source=auth_switcher')
sleep(3)
username = webdriver.find_element_by_name('username')
username.send_keys('yourUsername')
password = webdriver.find_element_by_name('password')
password.send_keys('yourPassword')
#instead of searching for the Button (Log In) you can simply press enter when you already selected the password or the username input element.
submit = webdriver.find_element_by_tag_name('form')
submit.submit()

You can copy the code and run it directly (even without a real username or password) To get the webdriver (chromedriver.exe) from ChromeDriver您可以复制代码并直接运行(即使没有真实的用户名或密码) 从ChromeDriver获取 webdriver (chromedriver.exe)

The instagram is applying some method to leave the dynamic id, xpath and css, every time a reload happens on the page the attributes change their values, being more difficult to click or to set values: instagram 正在应用一些方法来保留动态 id、xpath 和 css,每次在页面上重新加载时,属性都会更改它们的值,更难以点击或设置值:

在此处输入图片说明

The username field on Instagram is a ReactJS so you have to induce WebDriverWait and then invoke send_keys() method as follows : Instagram 上用户名字段是一个ReactJS,因此您必须引入WebDriverWait ,然后调用send_keys()方法,如下所示:

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

options = Options()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
browser = webdriver.Chrome(chrome_options=options, executable_path=r'C:\path\to\chromedriver.exe')
browser.get('https://www.instagram.com')
login_elem = browser.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div[2]/div[2]/p/a')
login_elem.click()
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='username']"))).send_keys("anon")

Browser Screenshot :浏览器截图:

浏览器截图

I solved it:我解决了:

#Locate the username field
unform = browser.find_element_by_name("username")
#Locate the password field
pwform = browser.find_element_by_name('password')

ActionChains(browser)\
    .move_to_element(unform).click()\
    .send_keys('test')\
    .move_to_element(pwform).click()\
    .send_keys('test')\
    .perform()

#Locate login button
login_button = browser.find_element_by_xpath(
'//*[@id="react-root"]/section/main/article/div[2]/div[1]/div/form/span/button')

#Click login button
login_button.click()

在这种情况下恕我直言最好使用这个: browser.find_element_by_name("Bermil18") / browser.find_element_by_name("1q56y3w5t9k0p3es8i1q")

Here's my solution for Sign In on Instagram这是我在 Instagram 上登录的解决方案

def login(self, username, password):
    """ Methods that log in to Instagram by taking user's credentials as parameters"""
    self.driver.get("https://www.instagram.com/accounts/login/")
    try:            
        self.driver.find_element_by_xpath("//input[@name=\"username\"]").send_keys(username) # filling username
        self.driver.find_element_by_xpath("//input[@name=\"password\"]").send_keys(password) # filling password
        self.driver.find_element_by_xpath("//button[@type=\"submit\"]").click()              # submit form
    except NoSuchElementException:
        print("Failed to log in: Unable to locate Username/Password/LogIn element(s)")

    # If login is unsuccessful, Instagram will show a message "Sorry, your password was incorrect. Please double-check your password."
    success = self.driver.find_elements_by_xpath("//p[@id = \"slfErrorAlert\"]")
    if len(success) == 0:
        print("Login successful!")
    else: 
        print("Sorry, sign in unsuccessful. Please double-check your credentials.")

See my Github repo for more: https://github.com/mlej8/InstagramBot有关更多信息,请参阅我的 Github 存储库: https : //github.com/mlej8/InstagramBot

def login(username,password):定义登录(用户名,密码):

driver.get(base_url)

time.sleep(3)
detail = driver.find_elements_by_class_name('_2hvTZ')
detail[0].clear()
detail[1].clear()
detail[0].send_keys(username)
detail[1].send_keys(password)
driver.find_element_by_class_name('L3NKy').click()
time.sleep(3)
for i in driver.find_elements_by_tag_name('button'):
    if i.text=='Not Now':
        i.click()
        break
time.sleep(3)
driver.find_element_by_class_name('HoLwm').click()

base url is intagram url .基本 url 是 intagram url 。 I have a made an instabot and you can find the code for logging in ,follow, unfollow ,like ,check posts in recent day ,etc in the following github link.我制作了一个 instabot,您可以在以下 github 链接中找到登录、关注、取消关注、查看最近的帖子等代码。 https://github.com/Devanshchowdhury2212/Instagram-Web-scraping- https://github.com/Devanshchowdhury2212/Instagram-Web-scraping-

This worked for me:这对我有用:

def login(self, username):
    self.driver = webdriver.Chrome()   
    self.driver.get('https://www.instagram.com/')
    sleep(1)
    username_input = self.driver.find_element_by_xpath(
        "//input[@name='username']")
    username_input.send_keys(username)
    password_input = self.driver.find_element_by_xpath(
        "//input[@name='password']")
    password_input.send_keys(pw)
    submit_btn = self.driver.find_element_by_xpath(
        "//button[@type='submit']")
    submit_btn.click()

    sleep(2) 
    save_your_login_info_not_now = self.driver.find_element_by_xpath("/html/body/div[1]/section/main/div/div/div/div/button")
    save_your_login_info_not_now.click()

You will notice that i am sending the variable pw instead of my actual password.您会注意到我发送的是变量 pw 而不是我的实际密码。 This is for security reasons.这是出于安全原因。 Make a new file called secrets.py and inside it, declare your password in the following format:创建一个名为 secrets.py 的新文件,并在其中按以下格式声明您的密码:

pw = '*********'

Try to select the field with尝试选择字段

unform = browser.find_element_by_xpath("//input[@name='username']")
unform.send_keys(<username>)

and for password和密码

browser.find_element_by_xpath("//input[@name='password']")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM