如何在Python中使用Selenium获取textContent

2024-05-29 05:00:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Selenium (Python)https://spamwc.de/收到电子邮件。在

在htmldom中它看起来像:document.getElementById("mails").textContent (它是有效的,当邮箱里没有邮件时,它会给出“…没有邮件…”的信息,这很好)

我希望使用硒也能得到同样的结果。在

我的代码:

        try:
            mails = self.driver.find_element_by_id("mails").getAttribute("outerHTML")
            print("mails:", mails)
        except:
            print("mails: no outerHTML")

        try:
            mails = self.driver.find_element_by_id("mails").getAttribute("innerHTML")
            print("mails:", mails)
        except:
            print("mails: no innerHTML")

        try:
            mails = self.driver.find_element_by_id("mails").getAttribute("textContent")
            print("mails:", mails)
        except:
            print("mails: no textContent")

结果(异常:'WebElement' object has no attribute 'getAttribute'):

^{pr2}$

当然,带有id="mails"的元素存在。在

例如当邮箱(例如。test@akkecuwa.ga)为空: document.getElementById('mails').textContent

结果: There are no mails for you, sorry.

我愿意接受任何建议。在


Tags: noselfidbydriverelementfinddocument
2条回答

我想你很可能愿意从这些邮件中获取文本。在

mails = self.driver.find_element_by_id("mails").get_attribute("outerHTML")
content = mails.text //just search for the correct method to get this text

您可能要检查多封邮件,所以不要使用“按id查找”“元素”;“按id查找所有元素”(它将查找符合您的选择器的所有元素),然后您可以循环查看这些元素的列表,并获取列表中包含的每个元素的内容。在

要调用的方法是get_attribute(),而不是getAttribute()。在那之后它应该能正常工作。在

    try:
        mails = self.driver.find_element_by_id("mails").get_attribute("outerHTML")
        print("mails:", mails)
    except:
        print("mails: no outerHTML")

    try:
        mails = self.driver.find_element_by_id("mails").get_attribute("innerHTML")
        print("mails:", mails)
    except:
        print("mails: no innerHTML")

    try:
        mails = self.driver.find_element_by_id("mails").get_attribute("textContent")
        print("mails:", mails)
    except:
        print("mails: no textContent")

相关问题 更多 >

    热门问题