【问题标题】:Unable to locate element when browser in background using Selenium当浏览器在后台使用 Selenium 时无法定位元素
【发布时间】:2021-12-19 21:43:12
【问题描述】:

我正在尝试自动化这个程序以在后台处理我的工作,但我发现当我没有在其他进程前面激活浏览器时它会给出“无法找到元素”错误(喜欢看)。它在 Twitter 上关注人们,但就像我希望程序完成它的工作一样。浏览器处于活动状态时一切都很顺利,但是当我在笔记本电脑上切换到其他作品时,即使元素可见,它也无法找到该元素。

我是新手,还在学习,所以我不知道 Selenium 是否有限制。

def to_follow_delay():
    def to_follow_delay_2():
        try:
            driver.get(next(urls))
            def follow_user():
                sleep(5)
                followuser = driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]/main/div/div/div/div/div/div[2]/div/div/div[1]/div/div[1]/div[2]/div[3]/div/div')
                sleep(5)
                followuser.click()
                #followuser = WebDriverWait(driver, 50).until(EC.presence_of_element_located((By.XPATH, '//*[@id="react-root"]/div/div/div[2]/main/div/div/div/div/div/div/div/div/div[1]/div[2]/div[1]/div[2]/div[2]/div/div')))
                print("Follow successful")
                print("--- %s seconds ---" % (time.time() - starting4))

                followedper_runcounter.set(followedper_runcounter.get() + 1)
                followedcounter.set(followedcounter.get() + 1)
                return operation_follow()

            timer4 = threading.Timer(tofollowdelayvalue_txt.get(), follow_user)
            timer4.start()
            starting4 = time.time()
        except StopIteration:
            print('No more urls.')
            return

       
    timer5 = threading.Timer(5, to_follow_delay_2)
    timer5.start()

【问题讨论】:

  • 1.您可以在无头模式下启动 chrome 并且您不会与页面 2 交互。(不确定它是否有效,但您可以尝试)是移动到元素,以便焦点切换回 chrome “action = ActionChains( driver) action.move_to_element(element).click().perform()
  • @Cassano 听起来您使用的是 Mac。对吗?
  • 不,我使用的是 Windows 10。
  • 你试过使用火狐吗?

标签: python selenium


【解决方案1】:

当您使用无头模式时,此问题通常会得到解决。 对于 Firefox,您必须包含的设置是

options = webdriver.FirefoxOptions()
options.add_argument('-headless')
driver = webdriver.Firefox(firefox_profile = profile, executable_path = 'C:\\some path\\geckodriver.exe', options=options)

【讨论】:

    猜你喜欢
    • 2015-06-08
    • 2021-03-31
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多