Python 我在用Selenium制作Instagram这样的机器人时遇到了问题

Python 我在用Selenium制作Instagram这样的机器人时遇到了问题,python,selenium,selenium-webdriver,instagram,bots,Python,Selenium,Selenium Webdriver,Instagram,Bots,我在用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)

我在用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)

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

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

因此,您可以使用
尝试
除了

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()
别忘了导入它:
来自selenium.common.exceptions导入NoSuchElementException

现在谈谈你应该使用的
睡眠


希望这对你有帮助

这里提供了一个查找hashtags追随者的示例。要实现完全自动化,只需进入我的github页面。这仅供参考和研究之用,因此,如果“未找到类”或“未找到元素”存在任何问题,只需更改检查元素并更改标记/类名。这是因为他们不断更改路径和名称

从selenium导入webdriver
从selenium.webdriver.common.keys导入密钥
从selenium.webdriver.common.action\u链导入ActionChains
导入时间
随机输入
从随机导入randint
导入操作系统
def update_文件():
将open('hashtags.txt')作为f:
main_list=f.read().splitlines()
返回(主列表)
def格式(num):
x=num.replace(',','')
num=int(x)
如果num>999和num99999:
x=num%1000000
y=num//1000000
返回(str(y)+'.+str(x)[0]+'M')
其他:返回(num)
br=webdriver.Chrome()
得到https://www.instagram.com/accounts/login/')
时间。睡眠(5)
br.通过名称(“用户名”)查找元素。发送密钥(“用户名”)
br.按名称(“密码”)查找元素。发送密钥(“密码”,密钥。输入)
时间。睡眠(5)
主\u列表=更新\u文件()
计数=0
尽管如此:
尝试:
得到https://www.instagram.com')
时间。睡眠(3)
如果在br.page\u源中“打开”:
x=br.通过类名称(“mt3GC”)查找元素
a=x.通过标签名称(“按钮”)查找元素
a[1]。单击()
时间。睡眠(2)
对于范围内的i(计数,len(主列表)):
标记=(str(主列表[i]))
a=tag.strip()
tag=a.lower()
a=标记。替换(“”,“”)
tag=a.replace('\n','')
a=标记。替换('\t','')
得到https://www.instagram.com/explore/tags/“+a)
印刷品(a)
时间。睡眠(7)
find=br.通过xpath(“/*[@class='g47SY']”)查找元素
时间。睡眠(2)
posts=查找[0]。文本
post=格式(posts)
打印(邮寄)
以open('posts.txt','a')作为f:
x=str(邮政)
f、 写入(“%s\n”%x)
将open('tags.txt','a')作为f:
x='#'+a
f、 写入(“%s\n”%x)
时间。睡眠(3)
计数+=1
例外情况除外,如e:
打印(e)
通过

非常感谢,它很有效。但在这之后,驱动程序会喜欢评论,因为类似评论的按钮和类似帖子的按钮具有相同的元素。您对跳过以前喜欢的帖子有什么建议吗?
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