import undetected_chromedriver.v2 as uc
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def main(url):
options = uc.ChromeOptions()
options.headless = True
driver = uc.Chrome(options=options)
driver.get(url)
try:
WebDriverWait(driver, 10).until(
EC.title_contains(('Reservations'))
)
print(driver.title)
except Exception as e:
print(type(e).__name__)
finally:
driver.quit()
if __name__ == "__main__":
main('https://www.example.com/')
如果CCD_ 1,则站点没有响应。我该怎么解决?
p.S正在寻求硒的解决方案。
使用Xvfb等虚拟显示器,这样就不需要在Linux服务器等无头机器上使用无头模式。
有一个Selenium Python框架,https://github.com/seleniumbase/SeleniumBase,内置集成到未检测到的chromedriver。运行测试时,将--uc
添加为SeleniumBase测试的pytest命令行选项。例如:
pytest --uc --xvfb
这可以让您在未检测到的chromedriver模式下,在Linux无头机器上成功运行SeleniumPython测试。(含硒基(
您可以使用以下内容进行测试,example.py
:
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_hyatt(self):
self.open("https://www.example.com/")
self.assert_in("Reservations", self.get_title())
print(self.get_title())
然后在运行时:
pytest example.py --uc --xvfb
==================== test session starts ====================
platform darwin -- Python 3.10.5, pytest-7.1.3, pluggy-1.0.0
rootdir: /Users/michael/github/SeleniumBase/examples, configfile: pytest.ini
plugins: html-2.0.1, xdist-2.5.0, forked-1.4.0, rerunfailures-10.2, ordering-0.6, cov-3.0.0, metadata-2.0.2, seleniumbase-4.3.8
collected 1 item
example.py Example Domain
.
==================== 1 passed in 8.68s