如何通过Selenium和Python将文本发送到Instagram中的用户名和密码字段

时间:2018-12-10 04:46:38

标签: python selenium selenium-webdriver instagram webdriverwait

我收到了关于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

这是我的代码 Commenter.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)

这是我遇到的最多问题的脚本,我尝试过按照扩展名的更改进行尝试,并且解决了其他一些小问题,现在大部分问题都困扰于这些

2 个答案:

答案 0 :(得分:0)

如果您读取了堆栈跟踪,则表示找不到登录按钮,因此您输入了错误的选择器。我不太确定您为什么仍要打电话,因为您不想在输入用户信息之前单击登录按钮。

尝试:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>
<button id="button" class="btn btn-default" type="submit">Search</button>

<div id="tbl"></div>

<div class="dropdown-menu" id="contextMenu">
  <a class="dropdown-item" href="#">Link 1</a>
  <a class="dropdown-item" href="#">Link 2</a>
</div>

答案 1 :(得分:0)

Instagram 中的用户名密码字段是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()