当前位置: 首页 > 知识库问答 >
问题:

我的Selenium驱动程序无法定位一个按钮,无论我如何指定它

江礼骞
2023-03-14

我正在“复制”Youtube视频中的代码(https://github.com/aj-4/ig-followers/blob/master/main.py)以更熟悉网络驱动程序。

我正在运行Linux Mint和Chromium 85。

它应该使用我的用户数据登录instagram,然后关闭出现“现在不行”的两个窗口。登录非常有效,在此过程中单击“提交”按钮也是如此,但是我的代码无法找到它必须单击才能继续的两个“现在不行”按钮。我已经尝试使用我通过检查Chromium中的按钮复制的完整XPath来指定按钮(就像我对提交按钮所做的那样)。此外,将按钮指定为("//按钮[包含(text(),'Not Now')]")也不起作用。我还尝试使用按钮类来完成它(如https://devhints.io/xpath所示)。

from selenium import webdriver
from time import sleep
from logindata import un , pw


class instabot:
    def __init__(self, un, pw):
        link = ('https://www.instagram.com')
        self.driver = webdriver.Chrome()
        self.driver.get(link)

    sleep(1)

    self.driver.find_element_by_xpath("//input[@name=\"username\"]")\
        .send_keys(un)
    self.driver.find_element_by_xpath("//input[@name=\"password\"]")\
        .send_keys(pw)

    sleep(1)

    self.driver.find_element_by_xpath("/html/body/div[1]/section/main/article/div[2]/div[1]/div/form/div/div[3]/button/div")\
        .click()

    self.driver.find_element_by_xpath("//button[contains(text(), 'Not Now')]")\
        .click()

    self.driver.find_element_by_xpath("//button[contains(text(), 'Not Now')]")\
        .click()

    sleep(2)


    print('FINISH TESTING? [y/n]')

    input() == (X)
    if X == 'y':
        self.driver.close()
    else:
        sleep(30)

    instabot(un, pw)

也不走运。我每次都得到同样的错误。

Traceback (most recent call last):
  File "instabot.py", line 41, in <module>
    instabot(un, pw)
  File "instabot.py", line 24, in __init__
    self.driver.find_element_by_xpath("//button[contains(text(), 'Not Now')]")\
  File "/home/anton/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "/home/anton/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element
    'value': value})['value']
  File "/home/anton/.local/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/home/anton/.local/lib/python3.6/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[contains(text(), 'Not Now')]"}
  (Session info: chrome=85.0.4183.83)

我对编码相当陌生,但即使是我也知道如何咨询谷歌。这对我没有帮助,所以我向你们求助。真诚感谢每一个回答。

提前感谢。

共有1个答案

蒲曦
2023-03-14

嗨,“现在不行”没有被点击,因为那些是selenium无法识别的弹出警告,点击“现在不行”

尝试使用以下命令,

driver.switch_to_alert()。dissolve()#这将使用“不是现在”选项来消除

 类似资料: