尝试使用selenium自动登录服务器时出现问题



你好,我写了这个脚本,试图自动登录e投睿服务器,然后获取投资组合服务器的利润和股权价值。

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('没有这样的元素:找不到元素:{quot;方法":quot;xpath"选择器"/html/body/ui布局/div/div/footer/et帐户余额/div/div[5]/span[1]';}\n(会话信息:headless chrome=86.0.4240.22(',None,['#0 0x55a2e8090d99','](

如果您尝试在http://superhost.gr/portfolio以前,这个脚本每半小时左右成功运行一次,就可以获取这两个值,其余时间都无法……但现在我说它根本无法访问网站,我不知道为什么。

页面正在加载,将错过元素。请使用等待让元素先加载,然后再抓取它们。

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

最新更新