运行 Python 包含来自 Azure Pipelines 的 selenium 的脚本。无法定位元素

Running Python script containing selenium from Azure Pipelines. Not able to locate elements

我有一个执行 selenium 任务的 Python 脚本。该脚本 运行 通过 Azure 管道使用以下 yaml 设置

# Python package
# Create and test a Python package on multiple Python versions. OK
# Add steps that analyze code, save the dist with the build record, publish to a PyPI-compatible index, and more:
# https://docs.microsoft.com/azure/devops/pipelines/languages/python

trigger: none

schedules:
- cron: "0/5 * * * 4"
  displayName: Run every couple of minutes
  branches:
    include:
    - develop

pool:
  vmImage: 'ubuntu-latest'
  name: Azure Pipelines

variables:
- group: Secrets&Passwords


stages:
- stage: Deployment
  displayName: Deployment stage
  jobs:
    - deployment: deploymentJob
      displayName: Deploy
      environment:
       name: Test
       resourceType: VirtualMachine
      strategy:
       runOnce:
         deploy:
           steps:
           - task: CmdLine@2
             inputs:
               script: |
                 python -m pip install --upgrade pip 
                 python -m pip install selenium 
                 python -m pip install pdfplumber 
                 python -m pip install pandas
             displayName: 'Install dependencies'
           - task: PythonScript@0
             displayName: 'Run a Python script'
             inputs:
              scriptPath: 'C:/azagent/A2/_work/Manuelle Ordrer/dist/main.py'
              arguments: -myvariable1 $(myvariable1) -myvariable2 $(myvariable2) -myvariable3 $(myvariable3) 





自从后台设置 运行s 以来,我已将 运行 的硒与 options.headless = True 指示为无头。当我在我的本地机器上手动启动 python 作业时它工作正常,但是当它通过 Azure Pipelines 运行 时,selenium 无法找到第一个元素并且我得到错误

"无法定位元素:{"method":"xpath","selector":"//*[@id="user"]"}(会话信息:headless chrome=92.0 .4515.159)"

有人知道为什么只有从 Azure Pipelines 运行连接它时才会出现这种情况吗?

"Unable to locate element: {"method":"xpath","selector":"//*[@id="user"]"} (Session info: headless chrome=92.0.4515.159)"

可能是selenium测试在Pipeline中运行时,网页加载速度会比本地加载慢

所以它可能会导致这个问题。

您可以尝试在 python 脚本中添加等待时间。

例如:

driver = webdriver.Chrome()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )
finally:
    driver.quit()