首页 > 解决方案 > 尝试使用 selenium 将登录过程自动化到服务器的问题

问题描述

您好,我编写了这个脚本来尝试自动登录 eToro 服务器,然后获取投资组合服务器的利润和权益值。

def get_profit():

profit = equity = ''

try:
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')              # Runs Chrome in headless mode.
    options.add_argument('--no-sandbox')            # Bypass OS security model
    options.add_argument('--disable-automation')
    options.add_argument('--disable-extensions')

    # Create new session
    driver = webdriver.Chrome( options=options, executable_path='/usr/bin/chromedriver' )
    driver.get( 'https://etoro.com/portfolio' )

    time.sleep(2)

    driver.find_element_by_id('username').send_keys('my_username')
    driver.find_element_by_id('password').send_keys('my_password')
    driver.find_element_by_css_selector('button.ng-binding').click()

    time.sleep(2)
    driver.save_screenshot( 'static/img/etoro.png' )

    profit = driver.find_element_by_xpath( '/html/body/ui-layout/div/div/footer/et-account-balance/div/div[5]/span[1]' ).text
    equity = driver.find_element_by_xpath( '/html/body/ui-layout/div/div/footer/et-account-balance/div/div[7]/span[1]' ).text
    driver.quit()
except Exception as e:
    profit = repr(e)

return profit, equity

问题是我不断收到相同的错误消息,即NoSuchElementException('no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/ui-layout/div/div /footer/et-account-balance/div/div[5]/span[1]"}\n (会话信息: headless chrome=86.0.4240.22)', None, ['#0 0x55a2e8090d99 ', ''])

如果您尝试在http://superhost.gr/portfolio运行我的 Web 应用程序脚本,您可以看到此输出。 在某些日子之前,该脚本能够通过每半小时左右成功运行一次来​​获取这两个值,其余的时代失败了......但现在我说它根本无法再访问该网站,我不知道为什么。

标签: pythonpython-3.xselenium

解决方案


页面正在加载并且会错过元素使用等待让元素首先加载然后抓取它们。

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

profit =  WebDriverWait(driver, 20).until(
EC.visibility_of_element_located((By.XPATH, "/html/body/ui-layout/div/div/footer/et-account-balance/div/div[5]/span[1]"))).text

推荐阅读