python - 尝试使用 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 应用程序脚本,您可以看到此输出。 在某些日子之前,该脚本能够通过每半小时左右成功运行一次来获取这两个值,其余的时代失败了......但现在我说它根本无法再访问该网站,我不知道为什么。
解决方案
页面正在加载并且会错过元素使用等待让元素首先加载然后抓取它们。
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
推荐阅读
- ios - 基于屏幕高度的约束常数
- php - 如何让 Laravel 数据透视表只使用 created_at?
- html - 上传前为数百个 html 文件批量替换 div 的内容
- python - 是否有类似于 R 中的 complete.cases 的等效 Python 函数
- javascript - Popover 材质 ui 的 event.currentTarget 问题
- java - 我可以使用原始类作为类型并仍然使用它的子类吗?
- html - .card 类中的列不会相互内联
- react-native - 在主容器上使用带有填充的 KeyboardAvoidingView
- python-3.x - create dataframe using the values from csv file, (Displays NaN values)
- java - Spring application from Standalone class without deploying WAR