像使用硒Python的instagram照片

时间:2018-08-24 21:52:13

标签: python-3.x selenium selenium-chromedriver instagram

我正在尝试为instagram编写自己的bot python selenium bot,以进行一些实验。我成功登录并在搜索栏中搜索了主题标签,这使我进入了以下网页: web page

但是我不知道如何喜欢feed中的照片,我试图对xpath和以下路径使用搜索:      “ // [@ id =“ reactroot”] / section / main / article / div 1 / div / div / div 1 / div 1 / a / div” 但这没有用,有人有主意吗?

3 个答案:

答案 0 :(得分:2)

首先,在您的情况下,建议使用Python的官方Instagram Api(documentation here on github)。

这将使您的机器人更简单,更易读,并且更轻松,更快速。这是我的第一个建议。

如果您确实需要使用Selenium,我也建议您下载Chrome here的Selenium IDE附加组件,因为它可以为您节省很多时间,请相信我。您可以找到一个不错的教程on Youtube

现在让我们讨论可能的解决方案及其实现。经过研究后,我发现帖子左下方的心脏图标的xpath的行为如下: 第一篇文章图标的xpath是:

xpath=//button/span

第二篇文章图标的xpath为:

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

第三篇文章图标的xpath为:

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

以此类推。 “文章”附近的第一个数字对应于帖子的编号。

enter image description here

因此,您可以设法获取所需帖子的编号,然后单击它:

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")

希望有帮助。让我知道是否还有其他问题。

答案 1 :(得分:0)

我正尝试做同样的事情) 这是一种工作方法。
首先,找到一类帖子(v1Nh3),然后捕获链接属性(href)。

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

答案 2 :(得分:0)

我实现了一个功能,该功能喜欢Instagram页面上的所有图片。它可以在“浏览”页面上使用,也可以仅在用户的配置文件页面上使用。

这就是我的做法。

首先,要从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")

此方法检查图片是否对下一张图片具有“下一张”按钮:

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