【问题标题】:I have a problem with making an Instagram-like bot with Selenium我在使用 Selenium 制作类似 Instagram 的机器人时遇到问题
【发布时间】:2019-10-25 22:38:48
【问题描述】:

我在使用 Selenium 制作类似 Instagram 的机器人时遇到了问题。 如果喜欢,我正在尝试编写通过图片的代码,但它不起作用。 这是我的代码:

    def Like_photoTags_and_commnet(self,hashtag,comment):

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

    pic_hrefs = []
    for i in range(1,3):
        driver.execute_script("window.scrollTo(0,document.scrollHeight);")
        time.sleep(2)
    #searching for pictures link
        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)))

        for pics in pic_hrefs:
            driver.get(pics)
            #if picture liked then continue
            if driver.find_element_by_xpath("//button/span[@aria-label='UnLike']"):
                continue
            else:
                driver.find_element_by_xpath("//button/span[@aria-label='Like']").click()

            if comment in driver.page_source:
                continue
            else:
                driver.find_element_by_class_name("Ypffh").click()
                for letter in comment:
                    driver.find_element_by_class_name("Ypffh").send_keys(letter)
                    time.sleep(random.randint(1,2))
                driver.find_element_by_class_name("Ypffh").send_keys(Keys.ENTER)
                time.sleep(5)

我在控制台中收到此错误。 问题出在第 52 行。你们有什么建议吗?

Traceback (most recent call last):
  File "C:/Users/behro/PycharmProjects/untitled/Test.py", line 52, in Like_photoTags_and_commnet
    if driver.find_element_by_xpath("//button/span[@aria-label='UnLike']"):
  File "C:\Users\behro\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\behro\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\behro\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\behro\PycharmProjects\untitled\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//button/span[@aria-label='UnLike']"}
  (Session info: chrome=74.0.3729.157)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17763 x86_64)

【问题讨论】:

    标签: python selenium selenium-webdriver instagram bots


    【解决方案1】:

    您正在尝试查找不存在的元素!因此错误:

    NoSuchElementException:消息:没有这样的元素

    所以你可以使用tryexcept

    for pics in pic_hrefs:
        driver.get(pics)
        #if picture liked then continue
        try:
            driver.find_element_by_xpath("//button/span[@aria-label='UnLike']"):
        except NoSuchElementException:
            driver.find_element_by_xpath("//button/span[@aria-label='Like']").click()
    

    别忘了导入:from selenium.common.exceptions import NoSuchElementException

    现在关于您的sleep,您应该改用WebDriverWait

    希望对您有所帮助!

    【讨论】:

    • 非常感谢它有效。但是在此之后,司机会喜欢 cmets,因为评论按钮和点赞按钮具有相同的元素。您有什么建议跳过以前喜欢的帖子吗?
    【解决方案2】:

    此处提供了一个寻找主题标签关注者的示例工作。为了完全自动化,去我的 github 页面吧。这仅用于信息和学习目的,因此如果对“找不到类”或“找不到元素”有任何问题,只需更改检查元素并更改标签/类名。这是因为他们不断更改路径和名称.

    https://www.github.com/deshwalmahesh

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.action_chains import ActionChains
    import time
    import random
    from random import randint
    import os
    
    
    def update_file():
        with open('hashtags.txt') as f:
            main_list=f.read().splitlines()
    
        return(main_list)
    
    def format(num):
        x=num.replace(',','')
        num=int(x)
        if num>999 and num<=999999:
            x=num%1000
            y=num//1000
            return(str(y)+'.'+str(x)[0]+'K')
        elif num>999999:
            x=num%1000000
            y=num//1000000
            return (str(y) + '.' + str(x)[0] + ' M')
        else: return (num)
    
    
    
    br=webdriver.Chrome()
    br.get('https://www.instagram.com/accounts/login/')
    time.sleep(5)
    br.find_element_by_name('username').send_keys('username')
    br.find_element_by_name('password').send_keys('password',Keys.ENTER)
    time.sleep(5)
    
    main_list=update_file()
    count=0
    while True:
        try:
            br.get('https://www.instagram.com')
            time.sleep(3)
            if "Turn on" in br.page_source:
                x=br.find_element_by_class_name('mt3GC')
                a=x.find_elements_by_tag_name('button')
                a[1].click()
                time.sleep(2)
            for i in range(count,len(main_list)):
                tag=(str(main_list[i]))
                a=tag.strip()
                tag=a.lower()
                a=tag.replace(' ','')
                tag=a.replace('\n','')
                a=tag.replace('\t','')
                br.get('https://www.instagram.com/explore/tags/'+a)
                print(a)
                time.sleep(7)
                find=br.find_elements_by_xpath("//*[@class='g47SY ']")
                time.sleep(2)
                posts=find[0].text
                post=format(posts)
                print(post)
                with open('posts.txt', 'a') as f:
                    x = str(post)
                    f.write('%s\n' % x)
    
                with open('tags.txt', 'a') as f:
                    x = '#'+a
                    f.write('%s\n' % x)     
    
            time.sleep(3)
    
            count+=1
    
        except Exception as e:
            print(e)
            pass
    
    
    

    【讨论】:

      猜你喜欢
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 2021-10-24
      • 2021-12-17
      • 2021-11-23
      • 2023-01-08
      相关资源
      最近更新 更多