简体   繁体   English

登录网站后,Selenium 驱动程序找不到任何元素 [Python]

[英]Selenium driver can't find any element after logging into a website [Python]

First of all if a similar topic occurred earlier I'm sorry but I couldn't find any problem like mine.首先,如果之前发生过类似的话题,我很抱歉,但我找不到像我这样的问题。

I would like to create a simple script which enters an e-mail website, log into my account and finds the amount of unread messages.我想创建一个简单的脚本,它可以进入电子邮件网站,登录我的帐户并查找未读邮件的数量。

This is the part with logging in这是登录的部分

from selenium import webdriver
from time import sleep

class sMailBot():
    def __init__(self):
        self.driver = webdriver.Chrome()

    def login(self):
        self.driver.get('website.com')

        sleep(2)

        btn_login = self.driver.find_element_by_xpath('//*[@id="username"]')
        btn_login.send_keys('my_username')

        btn_password = self.driver.find_element_by_xpath('//*[@id="password"]')
        btn_password.send_keys('my_password')

        btn_logintoaccount = self.driver.find_element_by_xpath('//*[@id="button"]')
        btn_logintoaccount.click()

        sleep(5)

It works really well.它真的很好用。 After logging into my mail account comments like driver.title or driver.current_url work.登录我的邮件帐户后,像driver.titledriver.current_url这样的评论工作。

Now I would like to scrape this part of html code:现在我想抓取这部分 html 代码:

<b>some_important_string_which_stores_the_amount_of_unread_mails</b>

I tried to do this using it's path我试图用它的路径来做到这一点

driver.find_element_by_xpath('//*[@id="MS_act1"]/span)

However it does not work.但是它不起作用。 Moreover I can't find any other elements from this side.此外,我无法从这一边找到任何其他元素。

I would like to highlight that I waiting even more than 10 seconds for the page to load.我想强调的是,我等待页面加载的时间甚至超过 10 秒。

The error which occurred发生的错误

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="MS_act1"]/span/b"}
  (Session info: chrome=80.0.3987.87)

As you asked I add some surrounding HTML code正如你所问的,我添加了一些周围的 HTML 代码

<span style="float: right">
<b>some_important_string_which_stores_the_amount_of_unread_mails</b> 
</span>

Please, don't use sleep , it's not a good choice for selenium.请不要使用sleep ,这不是硒的好选择。

Instead, use selenium waits:相反,使用硒等待:

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )
finally:
    driver.quit()

https://selenium-python.readthedocs.io/waits.html https://selenium-python.readthedocs.io/waits.html

First of all I will avoid using sleep.首先,我将避免使用睡眠。 You may try using WebDriverWait instead.您可以尝试改用WebDriverWait This will pause the browser until a given condition is satisfied.这将暂停浏览器,直到满足给定条件。

eg as follows例如如下

WebDriverWait(self.driver, 60).until(EC.presence_of_element_located((By.XPATH, "//button[text()='Login']")))

This will wait for 60 sec maximum for the element (button with text Login) to occur in the page.这将等待元素(带有文本登录的按钮)在页面中出现最多 60 秒。

After logging into your mail account commands like driver.title and driver.current_url works but they are not part of the DOM Tree .登录您的邮件帐户后,诸如driver.titledriver.current_url类的命令可以工作,但它们不是DOM Tree 的一部分。

The relevant HTML would have helped us to construct a canonical answer.相关的 HTML 将帮助我们构建规范的答案。 However to extract the desired text, you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies :但是,要提取所需的文本,您必须为visibility_of_element_located()引入WebDriverWait ,并且您可以使用以下任一定位器策略

  • Using CSS_SELECTOR and get_attribute("innerHTML") :使用CSS_SELECTORget_attribute("innerHTML")

     print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "[id^='MS_act'] span>b"))).get_attribute("innerHTML"))
  • Using XPATH and text attribute:使用XPATHtext属性:

     print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//*[starts-with(@id, 'MS_act')]//span/b"))).text)
  • Note : You have to add the following imports :注意:您必须添加以下导入:

     from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM