Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 views
in Technique[技术] by (71.8m points)

selenium - headless mode not working (python%selenuim)

I'm trying to make a spam dm Instagram bot I just get this error

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element

I just want it to work in headless mode and here is my code when I use a non-headless mode it just works I don't really know why so please help me

there is more code but im just importing the error line code which is the first

driver.find_element_by_xpath

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from time import sleep

def instsspamdm():
    user = input("Enter the username: ")
    password = input("Enter tha password: ")
    target = input("Target: ")
    mess = input("Target message: ")
    sleepTime = int(input("Sleep[sec]: "))
    delay = float(input("Delay[sec]: "))
    autoMode = input("Auto Mode[y/n]: ")
   
    if autoMode == "y":
        options = Options()
        options.headless = True
        driver = webdriver.Chrome(ChromeDriverManager().install(), options = options)
        driver.get("https://instagram.com")
        sleep(sleepTime)
        driver.find_element_by_xpath("/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div/div[1]/div/label/input").send_keys(user)  # Account Username
        driver.find_element_by_xpath("/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div/div[2]/div/label/input") 
            .send_keys(password)  # Account Password
        driver.find_element_by_xpath("/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div/div[3]/button") 
        y = 1

        while True:
            driver.find_element_by_xpath("/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea")
                .send_keys(mess)
            driver.find_element_by_xpath("/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[3]/button")
                .click()
            x = "Done Spam: "
            print(x, y)
            y += 1
            sleep(delay)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You also need to set the screen size when using headless.

options = Options()
options.add_argument("--headless")
options.add_argument("window-size=1920,1080")
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
driver.get("https://instagram.com")

Else it will use the default, which I believe is (800x400)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...