像带有硒的 instagram 照片 python

Like instagram photo with selenium python

我正在尝试编写我自己的 bot python 用于 instagram 的 selenium bot 来进行一些实验。我成功登录并在搜索栏中搜索主题标签,这将我带到了以下网页:

但我不知道如何给 Feed 中的照片点赞,我尝试使用 xpath 和以下路径进行搜索: “//[@id="reactroot"]/section/main/article/div1/div/div/div1/div1/a/div” 但是没有用,有人知道吗?

首先,对于你的情况,建议使用官方Instagram Api for Python (documentation here on github).

它会让你的机器人更简单、更易读,最重要的是更轻、更快。所以这是我的第一个建议。

如果您确实需要使用 Selenium,我还建议您下载用于 Chrome here since it can save you much time, believe me. You can find a nice tutorial on Youtube.

的 Selenium IDE 附加组件

现在让我们谈谈可能的解决方案及其实施。经过一些研究,我发现下面左下角的心形图标的 xpath post 表现如下: 第一个post的图标的xpath是:

xpath=//button/span

第二个post图标的xpath是:

xpath=//article[2]/div[2]/section/span/button/span

第三个post图标的xpath是:

xpath=//article[3]/div[2]/section/span/button/span

等等。 "article" 附近的第一个数字对应于 post.

的数字

所以你可以设法得到你想要的 post 的号码然后点击它:

def get_heart_icon_xpath(post_num):
    """
    Return heart icon xpath corresponding to n-post.
    """
    if post_num == 1:
      return 'xpath=//button/span'
    else:
      return f'xpath=//article[{post_num}]/div[2]/section/span/button/span'

try:
    # Get xpath of heart icon of the 19th post.
    my_xpath = get_heart_icon_xpath(19)
    heart_icon = driver.find_element_by_xpath(my_xpath)
    heart_icon.click()
    print("Task executed successfully")
except Exception:
    print("An error occurred")

希望对您有所帮助。如果发现其他问题,请告诉我。

我也在尝试这样做) 这是一个工作方法。
首先,我们找到class个帖子(v1Nh3),然后我们捕获link个属性(href)。

posts = bot.find_elements_by_class_name('v1Nh3')
links = [elem.find_element_by_css_selector('a').get_attribute('href') for elem in posts]

我实现了一个点赞 Instagram 页面中所有图片的功能。它可以用在 "Explore" 页面上,也可以简单地用在用户的个人资料页面上。

我是这样做的。

首先,为了从 Instagram 的主页导航到个人资料页面,我为 "SearchBox" 创建了一个 xPath,并为下拉菜单结果中对应于索引的元素创建了一个 xPath。

def search(self, keyword, index):
    """ Method that searches for a username and navigates to nth profile in the results where n corresponds to the index"""        
    search_input = "//input[@placeholder=\"Search\"]"
    navigate_to = "(//div[@class=\"fuqBx\"]//descendant::a)[" + str(index) + "]"
    try:
        self.driver.find_element_by_xpath(search_input).send_keys(keyword)
        self.driver.find_element_by_xpath(navigate_to).click()
        print("Successfully searched for: " + keyword)
    except NoSuchElementException:
        print("Search failed")

那我打开第一张图:

def open_first_picture(self):
    """ Method that opens the first picture on an Instagram profile page """
    try:             
        self.driver.find_element_by_xpath("(//div[@class=\"eLAPa\"]//parent::a)[1]").click()
    except NoSuchElementException:
        print("Profile has no picture") 

喜欢他们中的每一个:

def like_all_pictures(self):
    """ Method that likes every picture on an Instagram page."""  
    # Open the first picture
    self.open_first_picture()  
    # Create has_picture variable to keep track 
    has_picture = True     

    while has_picture:
        self.like()
        # Updating value of has_picture
        has_picture = self.has_next_picture()

    # Closing the picture pop up after having liked the last picture
    try:
        self.driver.find_element_by_xpath("//button[@class=\"ckWGn\"]").click()                
        print("Liked all pictures of " + self.driver.current_url)
    except: 
        # If driver fails to find the close button, it will navigate back to the main page
        print("Couldn't close the picture, navigating back to Instagram's main page.")
        self.driver.get("https://www.instagram.com/")


def like(self):
    """Method that finds all the like buttons and clicks on each one of them, if they are not already clicked (liked)."""
    unliked = self.driver.find_elements_by_xpath("//span[@class=\"glyphsSpriteHeart__outline__24__grey_9 u-__7\" and @aria-label=\"Like\"]//parent::button")
    liked = self.driver.find_elements_by_xpath("//span[@class=\"glyphsSpriteHeart__filled__24__red_5 u-__7\" and @aria-label=\"Unlike\"]")
    # If there are like buttons
    if liked:
        print("Picture has already been liked")
    elif unliked:
        try:   
            for button in unliked:
                button.click()
        except StaleElementReferenceException: # We face this stale element reference exception when the element we are interacting is destroyed and then recreated again. When this happens the reference of the element in the DOM becomes stale. Hence we are not able to get the reference to the element.
            print("Failed to like picture: Element is no longer attached to the DOM")

此方法检查图片是否有指向下一张图片的 "Next" 按钮:

def has_next_picture(self):
    """ Helper method that finds if pictures has button \"Next\" to navigate to the next picture. If it does, it will navigate to the next picture."""
    next_button = "//a[text()=\"Next\"]"
    try:
        self.driver.find_element_by_xpath(next_button).click()
        return True
    except NoSuchElementException:
        print("User has no more pictures")
        return False

如果您想了解更多信息,请随时查看我的 Github 存储库:https://github.com/mlej8/InstagramBot