0

我是 Python 新手。使用 Selenium 库进入 Tradingview.com 站点。

我编写了以下代码并使用 Xpath 和 CSS 选择器来给出地址和 Click 方法,但它不能正常工作。有没有人解决过这个问题?

import time
from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager

driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())

longInfo = ["xxx.gmail.com", "11"]

try:
    driver.get("https://www.tradingview.com/#signin")
    driver.set_page_load_timeout(20)
    driver.maximize_window()

# click email Button for logging page
    driver.find_element_by_xpath("/html/body/div[7]/div/div[2]/div/div/div/div/div/div/div[1]/div[4]/div/span").click()
    time.sleep(5)
    driver.find_element_by_css_selector(
    "#email-signin__user-name-input__e07a4b49-2f94-4b3e-a3f8-934a5744fe02").send_keys(longInfo[0])
    driver.find_element_by_css_selector(
    "#email-signin__password-input__e07a4b49-2f94-4b3e-a3f8-934a5744fe02").send_keys(longInfo[1])

# click sign in Button
    driver.find_element_by_xpath(
    "/html/body/div[7]/div/div[2]/div/div/div/div/div/div/form/div[5]/div[2]/button/span[2]").click()

    input("type for exit")

    driver.quit()
except Exception as e:
    print(e)
    driver.quit()
4

2 回答 2

0

看起来你已经使用了它的动态定位器,你需要用更好的方法来识别元素。

导航时所需的同步时间。

使用显式等待并等待元素可点击。

longInfo = ["xxx.gmail.com", "11"]
driver.get("https://www.tradingview.com/#signin")
wait=WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Email']"))).click()
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[name='username']"))).send_keys(longInfo[0])
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[name='password']"))).send_keys(longInfo[1])
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[.//span[contains(., 'Sign in')]]"))).click()

使用以下库。

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
于 2022-02-23T15:42:30.520 回答
0

id属性的这些值:

  • 电子邮件登录__用户名输入__e07a4b49-2f94-4b3e-a3f8-934a5744fe02
  • 电子邮件登录__密码输入__e07a4b49-2f94-4b3e-a3f8-934a5744fe02

是动态生成的,每次您重新访问网页时都会发生变化。相反,您需要使用基于静态属性的定位器策略。


解决方案

要登录Trading View网站,您需要为element_to_be_clickable()引入WebDriverWait,您可以使用以下定位器策略

driver.get("https://www.tradingview.com/#signin")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Email']"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='username']"))).send_keys("matin_mhz@stackoverflow.com")
driver.find_element(By.XPATH, "//input[@name='password']").send_keys("matin_mhz" + Keys.RETURN)

注意:您必须添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
于 2022-02-23T21:38:40.370 回答