【发布时间】:2022-01-23 10:45:20
【问题描述】:
我正在编写一个网页抓取脚本,它会自动登录到我的电子邮件帐户并发送一条消息。
我已将代码编写到浏览器单击“新消息”按钮的位置。之后会打开一个新窗口(或框架?),我可以在其中输入收件人地址、主题和消息。
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
myPassword = 'xxxxxxxxxxxxxxxx'
browser = webdriver.Firefox() # Opens Firefox webbrowser
browser.get('https://protonmail.com/') # Go to protonmail website
loginButton = WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "a.btn-ghost:nth-child(1)")))
loginButton.click()
usernameElem = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#username")))
usernameElem.send_keys("first.last@protonmail.com")
passwordElem = browser.find_element_by_css_selector("#password")
passwordElem.send_keys(myPassword)
anmeldenButton = browser.find_element_by_css_selector(".button")
anmeldenButton.click()
newMessage = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[1]/div[3]/div/div/div[1]/div[2]/button")))
newMessage.click()
addressElem = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#to-composer-1591")))
addressElem.send_keys('first.last@mail.com')
在以下行的第一行,我得到一个 TimeoutException 错误:
addressElem = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#to-composer-1591")))
addressElem.send_keys('asdf')
我认为发生错误是因为浏览器不知道在哪里找到元素,对吗?
“新消息”按钮的源代码如下:
<button class="button button-large button-solid-norm text-bold mt0-25 w100 no-mobile" aria-busy="false" type="button" data-testid="sidebar:compose" aria-describedby="tooltip-8">Neue Nachricht</button>
新窗口或框架的源代码:
<span class="flex-item-fluid p0-5 pr1 pl0-75 text-ellipsis user-select-none cursor-move">Neue Nachricht</span>
我不确定我是否以正确的方式解决问题。我试图在源代码中查找信息,这有助于浏览器找到正确的元素并使用 .switch_to_window() 或 .switch_to_frame() 方法。首先,我不确定是否真的是切换到新窗口或框架的问题(我真的不知道它们之间的区别)。第二:如何实现切换到新元素,让浏览器可以应用 .send_keys() 方法?
【问题讨论】:
-
希望这有帮助 => 这是因为您的驱动程序没有切换到新窗口。你可以参考这个 => geeksforgeeks.org/…
-
我建议你阅读一下这个 => driver.window_handles
-
请分享您的代码试用版。如果可能包括指向您正在处理的页面的链接
-
好的,我现在已经在 OP 中分享了我的代码。
-
当你点击
new Message按钮时会发生什么?如果它是一个新窗口,您会通过肉眼看到一个新的浏览器实例,但如果它是一个 iframe,您需要查看 HTMLDOM 以查看该框架是否存在
标签: python selenium selenium-webdriver web-scraping