简体   繁体   中英

selenium python for creating a instagram login liker bot

I am using selenium for python to create a simple liker bot for instagram. The idea is to like the first photo of a tag (in this example is "sunset"). It correctly selects the first photo but does not insert a like.

The code is as follows:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

from time import sleep

import User_data

chrome_options=Options()

chrome_options.add_argument('--lang=en')
browser = webdriver.Chrome(chrome_options=chrome_options)

browser.get("https://www.instagram.com/accounts/login/")
sleep(1)

browser.find_element_by_name("username").send_keys(User_data.username)
browser.find_element_by_name("password").send_keys(User_data.password)

sleep(1)

browser.find_element_by_xpath('//*[@id="react-root"]/section/main/div/article/div/div[1]/div/form/div[3]/button').click()

sleep(1)
browser.get("https://www.instagram.com/explore/tags/sunset/")

sleep(1)
browser.find_element_by_xpath("//article/div[2]/div/div/div/a/div/div[2]").click()
sleep(1)
browser.find_element_by_xpath("//button/span[contains(@class. 'glyphsSpriteHeart__outline__24__grey_9 u-__7') ]").click()

The reason you're unable to Log In is because your code is unable to find the element by xpath you specified. That is probably because the xpath that you provide is not supported.

I have found a workaround for this where I use the function find_elements_by_tag_name() which returns me the list of buttons, and with simple iteration I found that the second button returned corresponds to the Log In button on Instagram. So here's a working code that you will find useful.

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

from time import sleep

import User_data

chrome_options=Options()

chrome_options.add_argument('--lang=en')
browser = webdriver.Chrome(chrome_options=chrome_options)

browser.get("https://www.instagram.com/accounts/login/")
sleep(1)

browser.find_element_by_name("username").send_keys(User_data.username)
browser.find_element_by_name("password").send_keys(User_data.password)

sleep(2)

buttons = browser.find_elements_by_tag_name('button')
for button_element in buttons:
    print(button_element.text)     #- This will print the text of the buttons present

This will print you the text fields of all the buttons: Output:

Show
Log in
Log in with Facebook

These are the three buttons that come in my output, and since I have to click on the button with Log in in it's text, which is the second element from my list buttons[] , I use index 1 to denote that and click it.

buttons[1].click()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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