【问题标题】:How to send text to username and password field in Instagram through Selenium and Python如何通过 Selenium 和 Python 向 Instagram 中的用户名和密码字段发送文本
【发布时间】:2018-12-10 04:46:37
【问题描述】:

我收到的 python 程序的错误消息是:

   C:\Users\chanm\AppData\Local\Programs\Python\Python37-32\python.exe C:/Users/chanm/OneDrive/Desktop/bot/Commenter.py
    Traceback (most recent call last):
      File "C:/Users/chanm/OneDrive/Desktop/bot/Commenter.py", line 133, in <module>
        com.login()
      File "C:/Users/chanm/OneDrive/Desktop/bot/Commenter.py", line 28, in login
        login_button = driver.find_element_by_xpath("//a[@href='/accounts/login/']")
      File "C:\Users\chanm\AppData\Local\Programs\Python\Python37-32\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\chanm\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
        'value': value})['value']
      File "C:\Users\chanm\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
        self.error_handler.check_response(response)
      File "C:\Users\chanm\AppData\Local\Programs\Python\Python37-32\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":"//a[@href='/accounts/login/']"}
      (Session info: chrome=71.0.3578.80)
      (Driver info: chromedriver=2.44.609538 (b655c5a60b0b544917107a59d4153d4bf78e1b90),platform=Windows NT 10.0.17134 x86_64)
Process finished with exit code 1

这是我的代码 评论者.py

import time
import random
import re
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException
from chatterbot.trainers import ListTrainer
from chatterbot import ChatBot


class Commenter:

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

    """closing browser"""
    def closeBrowser(self):
        self.driver.close()

    """login in to Instagram"""
    def login(self) -> object:
        driver = self.driver
        driver.get("https://www.instagram.com/")
        time.sleep(2)
        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)

    """getting pictures on a hashtag page"""
    def get_pictures_on_page(self, hashtag, scrolls=int):
        self.driver.get("https://www.instagram.com/explore/tags/" + hashtag + "/")
        time.sleep(2)

        # gathering photos
        pic_hrefs = []
        for i in range(1, scrolls):
            try:
                self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
                time.sleep(2)
                # get tags
                hrefs_in_view = self.driver.find_elements_by_tag_name('a')
                # finding relevant hrefs
                hrefs_in_view = [elem.get_attribute('href') for elem in hrefs_in_view if
                                 hashtag 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
        return pic_hrefs

    """write comment in text area using lambda function"""
    def write_comment(self, comment_text):
        try:
            comment_button = lambda: self.driver.find_element_by_link_text('Comment')
            comment_button().click()
        except NoSuchElementException:
            pass

        try:
            comment_box_elem = lambda: self.driver.find_element_by_xpath("//textarea[@aria-label='Add a comment…']")
            comment_box_elem().send_keys('')
            comment_box_elem().clear()
            for letter in comment_text:
                comment_box_elem().send_keys(letter)
                time.sleep((random.randint(1, 7) / 30))

            return comment_box_elem

        except StaleElementReferenceException and NoSuchElementException as e:
            print(e)
            return False

    """actually post a comment"""
    def post_comment(self, comment_text):
        time.sleep(random.randint(1,5))

        comment_box_elem = self.write_comment(comment_text)
        if comment_text in self.driver.page_source:
            comment_box_elem().send_keys(Keys.ENTER)
            try:
                post_button = lambda: self.driver.find_element_by_xpath("//button[@type='Post']")
                post_button().click()
                print('clicked post button')
            except NoSuchElementException:
                pass

        time.sleep(random.randint(4, 6))
        self.driver.refresh()
        if comment_text in self.driver.page_source:
            return True
        return False

    """grab comments from a picture page"""
    def get_comments(self):
        # load more comments if button exists
        time.sleep(3)

        try:
            comments_block = self.driver.find_element_by_class_name('Xl2Pu')
            comments_in_block = comments_block.find_elements_by_class_name('gElp9')
            comments = [x.find_element_by_tag_name('span') for x in comments_in_block]
            user_comment = re.sub(r'#.\w*', '', comments[0].text)

        except NoSuchElementException:
            return ''
        return user_comment

    """have bot comment on picture"""
    def comment_on_picture(self):
        bot = ChatBot('YouTubeChatBot')
        bot.set_trainer(ListTrainer)
        picture_comment = self.get_comments()
        # user's comment and bot's response
        response = bot.get_response(picture_comment).__str__()
        print("User's Comment", picture_comment)
        print("Bot's Response", response)
        return self.post_comment(response)


com: Commenter = Commenter(username='username', password='password')
com.login()

for pic in com.get_pictures_on_page(hashtag='gaming', scrolls=5)[1:]:
    com.driver.get(pic)
    time.sleep(3)
    print('Posted Comment:', com.comment_on_picture())
    time.sleep(3)

这是我遇到的最多问题的脚本 我已经尝试过更改扩展名和其他小问题,它解决了大多数问题,现在我被这些问题困住了

【问题讨论】:

  • 错误信息看起来很清楚,没有与//a[@href='/accounts/login/匹配的元素。
  • 在我的程序文件中有
  • 由于您尚未发布您正在处理的 HTML,因此任何人都无法告诉您如何解决。
  • 我检查了所有的拼写,但它仍然生我的气
  • 我刚刚查看了www.instagram.com 的HTML 源代码,没有/accounts/login/

标签: python selenium selenium-webdriver instagram webdriverwait


【解决方案1】:

Instagram 中的 usernamepassword 字段是 JavaScript 启用元素,因此您必须诱导 WebDriverWait使所需的元素可点击,您可以使用以下解决方案:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

options = Options()
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get('https://www.instagram.com')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href='/accounts/login/?source=auth_switcher']"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[name='username'][aria-label='Phone number, username, or email']"))).send_keys("JRProgrammer")
driver.find_element_by_css_selector("input[name='password'][aria-label='Password']").send_keys("JRProgrammer")
driver.find_element_by_xpath("//button[text()='Log in']").click()

【讨论】:

    【解决方案2】:

    如果您阅读堆栈跟踪,它会说找不到登录按钮,因此您输入了错误的选择器。我不确定您为什么要调用它,因为您不想在输入用户信息之前单击登录按钮。

    试试:

        def login(self) -> object:
            driver = self.driver
            driver.get("https://www.instagram.com/")
            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)
            login_button = driver.find_element_by_css_selector("button[type='submit']")  
            login_button.click()
            time.sleep(2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 1970-01-01
      • 2019-06-02
      • 2018-12-26
      相关资源
      最近更新 更多