【问题标题】:I have a problem with a Instagram like bot with Python Selenium我对带有 Python Selenium 的 Instagram 之类的机器人有疑问
【发布时间】:2020-06-04 21:34:06
【问题描述】:

嘿,伙计们,我是 python 新手,我学习了 java 和 Pascal,是的,我想学习如何将 instagram 机器人与 python 一起使用并观看了 youtube 视频,但我的问题是机器人只是挑选图片并切换到下一个一个不喜欢它,所以我认为它找不到喜欢的按钮。

我认为问题出在 #Liking photos 我尝试更改 xpath 很多次,但它最终并不喜欢一张图片。 提前致谢

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
import time
import random
import sys


def print_same_line(text):
    sys.stdout.write('\r')
    sys.stdout.flush()
    sys.stdout.write(text)
    sys.stdout.flush()


class InstagramBot:

    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.driver = webdriver.Chrome()

    def closeBrowser(self):
        self.driver.close()

    def login(self):
        driver = self.driver
        driver.get("https://www.instagram.com/")
        time.sleep(3)
       #login_button = driver.find_element_by_xpath("//a[@href='/accounts/login/']")
       #login_button.click()
        time.sleep(2)
        user_name_elem = driver.find_element_by_xpath("//input[@name='username']")
        user_name_elem.clear()
        user_name_elem.send_keys(self.username)
        passworword_elem = driver.find_element_by_xpath("//input[@name='password']")
        passworword_elem.clear()
        passworword_elem.send_keys(self.password)
        passworword_elem.send_keys(Keys.RETURN)
        time.sleep(2)


    def like_photo(self, hashtag):
        driver = self.driver
        driver.get("https://www.instagram.com/explore/tags/" + hashtag + "/")
        time.sleep(2)

        # gathering photos
        pic_hrefs = []
        for i in range(1, 4):
            try:
                driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
                time.sleep(2)
                # get tags
                hrefs_in_view = driver.find_elements_by_tag_name('a')
                # finding relevant hrefs
                hrefs_in_view = [elem.get_attribute('href') for elem in hrefs_in_view
                                 if '.com/p/' in elem.get_attribute('href')]
                # building list of unique photos
                [pic_hrefs.append(href) for href in hrefs_in_view if href not in pic_hrefs]
                # print("Check: pic href length " + str(len(pic_hrefs)))
            except Exception:
                continue

        # Liking photos
        unique_photos = len(pic_hrefs)
        for pic_href in pic_hrefs:
            driver.get(pic_href)
            time.sleep(2)
            driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            try:
             time.sleep(random.randint(2, 4))
             #I think the problem is somewhere at the xpath
             like_button = lambda:  driver.find_element_by_xpath("//button/span[@aria-label='Like']").click()
             like_button().click()
             time.sleep(2)

                for second in reversed(range(0, random.randint(18, 28))):
                    print_same_line("#" + hashtag + ': unique photos left: ' + str(unique_photos)
                                    + " | Sleeping " + str(second))
                   time.sleep(1)
            except Exception as e:
                time.sleep(2)
            unique_photos -= 1

if __name__ == "__main__":

    username = "USERNAME"
    password = "PASSWORD"

    enesIG = InstagramBot("myIGloginname", "myIGPassword")
    enesIG.login()
    enesIG.like_photo('newyork')

    hashtags = ['amazing', 'beautiful', 'adventure', 'photography', 'nofilter',
                'newyork', 'artsy', 'alumni', 'lion', 'best', 'fun', 'happy',
                'art', 'funny', 'me', 'followme', 'follow', 'cinematography', 'cinema',
                'love', 'instagood', 'instagood', 'followme', 'fashion', 'sun', 'scruffy',
                'street', 'canon', 'beauty', 'studio', 'pretty', 'vintage', 'fierce']

    while True:
        try:
            # Choose a random tag from the list of tags
            tag = random.choice(hashtags)
            ig.like_photo(tag)
        except Exception:
            ig.closeBrowser()
            time.sleep(60)
            enesIG = InstagramBot(username, password)
            enesIG.login()

当前的错误是这个。当我更改like按钮上的xpath时,还会出现其他错误。

C:\Python38-32>Instagram_Bot3.py
  File "C:\Python38-32\Instagram_Bot3.py", line 78
    for second in reversed(range(0, random.randint(18, 28))):
    ^
IndentationError: unexpected indent

【问题讨论】:

    标签: python selenium instagram


    【解决方案1】:

    试试这个 xpath

    //*[name()='svg'][@aria-label='Like']/parent::button
    

    您试图作为span 访问的实际上是svg 元素,因此这似乎可以准确找到它。您可能会遇到其他一些问题。在本地测试时,我最终使用了

    like_button = driver.find_element_by_xpath("//*[name()='svg'][@aria-label='Like']/parent::button")
    driver.execute_script("arguments[0].click()", like_button)
    

    它使用 javascript 点击“喜欢”按钮。这似乎工作得相当可靠。

    此外,您引用的错误完全是由于您的代码的格式。在本地测试您的代码时,我可以通过复制它上面的行之前的空格并将其粘贴到该行中来解决这个问题,但是您真的应该始终如一地使用制表符。使用 Python 混合制表符和空格可能会很烦人。

    【讨论】:

    • 嘿,非常感谢您提供正确的 xpath。我还通过正确格式化它来修复我的错误。 Javascript Idea 也不错,但是当我尝试时,同样的情况又发生了。它不喜欢这张照片。我把它的样子记录在案。我有时间请看一下:) streamable.com/6faznj
    猜你喜欢
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 2019-10-25
    • 2013-06-20
    相关资源
    最近更新 更多