Python代码在本地运行,但不能在服务器上运行(带有硒的Discord机器人)

我的代码接受用户输入,并使用它来搜索网页上的项目。它会抓取网页的html代码,以获取显示结果的项目:

driver = webdriver.Chrome()
driver.get(urlItem)
#this last line is the one that's not working on heroku
item_list = driver.find_elements_by_class_name('price-history-link')

这是html代码:

<ul class="no-padding small-block-grid-3 large-block-grid-5 text-center word-wrap-break-word">
<li>
<a href="/item/7399/"><img src="/assets/imgs/items/7399.gif" alt="A Grey Faerie Doll" title="A Grey Faerie Doll" class="item-result-image"></a><br><a href="/item/7399/">A Grey Faerie Doll</a>
<br><span class="text-small"><a href="/item/7399/price-history/" class="price-history-link" title="October 31,2019">2,400,000 NP</a></span>
</li>
</ul>

当我在本地运行代码时,该机器人可以完美运行。当我从托管站点(heroku)运行完全相同的代码时,它不返回任何项目。 我以为这可能是加载问题,所以我添加了一个:

WebDriverWait(driver,10).until(ec.visibility_of_element_located((By.CLASS_NAME,"price-history-link")))

使用此代码后,它会返回一个异常(仅当在托管站点上运行时,才在我的PC上运行时完美运行)

  

引发TimeoutException(消息,屏幕,堆栈跟踪)   selenium.common.exceptions.TimeoutException:消息:

是的,异常到此结束,实际上并没有向我显示该消息。

我真的不明白为什么它在heroku上不起作用... 任何帮助都非常感谢!

编辑:捕获NoSuchElementException异常,但没有捕获任何异常

bingojqliu5 回答:Python代码在本地运行,但不能在服务器上运行(带有硒的Discord机器人)

您看对了。 WebDriverWait()expected_conditions()一起会在失败时始终返回 TimeoutException

  

您可以在Random Selenium E2e Tests Fail because of timeouts on Azure DevOps but work locally and with remote Selenium (BrowserStack Automate)

中找到详细的讨论

此用例

当您将Locator Strategy CLASS_NAME用作 price-history-link 时,此CLASS_NAME可能也与某些隐藏元素相关联。因此,当您使用find_elements_by_class_name()时,将标识元素visibility_of_element_located()产生TimeoutException的地方。


解决方案

要与find_elements_by_class_name()WebDriverWait()一起模拟expected_conditions(),则需要为visibility_of_all_elements_located()引入 WebDriverWait ,您可以使用以下解决方案:

  • 使用CSS_SELECTOR

    item_list = WebDriverWait(driver,20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,"a.price-history-link[href$='/price-history/'][title*='20']")))
    
  • 使用XPATH

    item_list = WebDriverWait(driver,20).until(EC.visibility_of_all_elements_located((By.XPATH,"//a[@class='price-history-link' and contains(@href,'/price-history/')][contains(.,'NP')]")))
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
本文链接:https://www.f2er.com/3169127.html

大家都在问