python - 如何在 Python 中使用 selenium 登录网站?

标签 python python-3.x selenium selenium-webdriver

我正在尝试使用我的凭据登录此网站。然而,虽然我在他们的 html 中提供了他们的内容,但它不起作用

目前,我有

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

CHROMEDRIVER_PATH = './chromedriver'

chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("start-maximized")
chrome_options.add_argument("--disable-blink-features")
chrome_options.add_argument("--disable-blink-features=AutomationControlled")

LOGIN_PAGE = "https://www.seekingalpha.com/login"
ACCOUNT = "account.com"
PASSWORD = "password"

driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH, chrome_options=chrome_options)
driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
driver.execute_cdp_cmd('Network.setUserAgentOverride', {"userAgent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.53 Safari/537.36'})

driver.get("https://www.seekingalpha.com/login")
username = driver.find_element_by_name("email")
username.send_keys(ACCOUNT)
password = driver.find_element_by_name("password")
password.send_keys(PASSWORD)

submit_button = driver.find_element_by_css_selector("button._60b46-2mbi1 _60b46-2LbhQ _60b46-1HfKK _60b46-qZydf _60b46-1uOHx _60b46-2NDcV _60b46-3YvwX _60b46-22lGb _60b46-1qE-_ _60b46-3DOuR _60b46-1UPRS _12b23-2JWwg _60b46-EQJB_")
submit_button.click()


driver.get("https://seekingalpha.com/article/4414043-agenus-inc-agen-ceo-garo-armen-on-q4-2020-results-earnings-call-transcript")
text_element = driver.find_elements_by_xpath('//*')

text = text_element

for t in text:
    print(t.text)

我不断得到

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"[name="email"]"}
  (Session info: headless chrome=90.0.4430.212)

最佳答案

这个问题可以借助显式等待来解决。请参阅下面的代码:

driver = webdriver.Chrome("C:\\Users\\etc\\Desktop\\Selenium+Python\\chromedriver.exe", options=options)
wait = WebDriverWait(driver, 30)
driver.get("https://www.seekingalpha.com/login")
wait.until(EC.element_to_be_clickable((By.NAME, "email"))).send_keys("some user name")
wait.until(EC.element_to_be_clickable((By.ID, "signInPasswordField"))).send_keys("your password")
wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Sign in']"))).click()
print("Logged in")

阅读有关显式等待的更多信息 here

关于python - 如何在 Python 中使用 selenium 登录网站?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67528971/

相关文章:

python - FastAPI - 未填充 ENUM 类型模型

python - Numpy:索引 3D 数组,最后一个轴的索引存储在 2D 数组中

python - 如何使用Python将unicode字符串转换为真正的字符串

python - 以 DAG 方式调度作业

Python:用其他字符串包围字符串的一部分?

python - 如何在 Ubuntu 上使用 Python 查找 Apache2 的配置错误?

Python线程未并行处理

javascript - 通过CSS获取css值并在Selenium中使用

html - 当元素有更多带有文本的元素时获取该元素的文本

Selenium WebDriver 无需等待页面加载即可进入页面