首页 > 解决方案 > Selenium Select from dropdown element not found in heroku,但在本地找到

问题描述

我创建了一个 python 脚本,可以将温度本身输入到网站中,并且可以在本地运行。当我将它部署到 Heroku 中时,它也能正常工作。我还根据需要安排我的应用程序在早上和下午运行一次。

from selenium import webdriver
import os
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
import time


chrome_options = webdriver.ChromeOptions()
chrome_options.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--headless')


browser = webdriver.Chrome(executable_path=os.environ.get("CHROMEDRIVER_PATH"), chrome_options=chrome_options)
 
browser.get('https://temptaking.ado.sg/group/e306686f4e962fec4c8b20ea8e60d1fe')



select = Select(browser.find_element_by_id('member-select'))

select.select_by_value('79563')

browser.find_element_by_id("ep1").send_keys("2084")

browser.find_element_by_id("td1").send_keys("36")


browser.find_element_by_id("td3").send_keys("5")

browser.find_element_by_class_name("btn")
submit = browser.find_element_by_class_name("btn-warning")

submit.click()

time.sleep(5)

subbmit = browser.find_element_by_id("submit-temp-btn")

subbmit.click()

browser.close()

但是,有一个问题。该网站有一个上午和下午的下拉菜单,它会自动更改(下午 12 点之后的下午)。但是,当我下午运行脚本时,仍然选择了 AM 下拉菜单。

然后,如果不是上午 8 点,我尝试再输入几行以从下拉列表中选择 PM 选项,这是我安排我的应用程序在早上运行的时间,使用以下行。

hour = dt.datetime.now().hour

if hour == 7:

    select2 = Select(browser.find_element_by_id('meridies-input'))
    time.sleep(3)
    select2.select_by_value('AM')
    select2.select_
else:
    select2 = Select(browser.find_element_by_id('meridies-input'))
    time.sleep(3)
    select2.select_by_value('PM')

但是,一旦我将它推入 heroku 并尝试运行脚本,就会遇到 NoSuchElementException 错误,它无法找到值“PM”。我曾尝试使用 index、select_by_visible_Text,甚至 xpath,都给出了类似的错误,无法找到___。我已经包含了 time.sleep,因为我认为它在加载时遇到了问题,但无济于事。让我感到困惑的是,我在代码的另一部分使用了下拉菜单中的选择,但这没有问题,只是这个特定的块。

我被这个小问题拖了后腿,这让我非常烦恼。请帮忙。

标签: pythonseleniumdatetimeherokuhtml-select

解决方案


而不是无头使用虚拟显示。(可能你的元素依赖于 javascript)

在所有操作 stop() 显示后初始化 chrome 之前使用 start() 显示。

from pyvirtualdisplay import Display
from selenium import webdriver
import os
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
import time

display = Display(visible=False, size=(800, 600))
display.start()

chrome_options = webdriver.ChromeOptions()
chrome_options.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--no-sandbox')
browser = webdriver.Chrome(executable_path=os.environ.get("CHROMEDRIVER_PATH"), chrome_options=chrome_options)

# your code
#########

# at end stop display
display.stop()

推荐阅读