Why does running Javascript in Python + Seleniuim get an undefined error?

问题: I'm trying to use Javascript to get a table body element on a page, if I run it as soon as I can I get undefined, but if I wait a few seconds it works. def get_row_list(b...

问题:

I'm trying to use Javascript to get a table body element on a page, if I run it as soon as I can I get undefined, but if I wait a few seconds it works.

def get_row_list(browser):
    table_body = browser.execute_script("""
        var tbody = document.getElementsByClassName("sortable")[0].children[1]
        return tbody
    """)
    while table_body == None:
        browser.execute_script("""
            var tbody = document.getElementsByClassName("sortable")[0].children[1]
            return tbody
        """)
    return table_body.find_elements_by_tag_name("tr")

If I run this too early I get Message: TypeError: document.getElementsByClassName(...)[0] is undefined


回答1:

I don't know if this works while working with JS in Python, but this sure helps while executing JS only.

Try:

table_body = browser.execute_script("""
    document.onload = function() {
      document.getElementsByClassName("sortable")[0].children[1];
      return tbody;
    }
""")

This should wait till your DOM is loaded and then looks for the element required


回答2:

The element sortable is not rendered yet...

Ues WebDriverWait to wait for the element to load:

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

WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.CLASS_NAME, "sortable"))

Hope this helps you!


回答3:

To get to why this is not working, the crucial component here is the error you recieve when it is too early.

Basically, the document has not loaded. This means that your DOM (Document Object Model) representation is not ready to be parsed yet.

Essentially what your code is going, is that the browser is executing the script before waiting for the document to be loaded. To get around this emit a signal when the DOM is ready.

  • 发表于 2019-02-15 15:54
  • 阅读 ( 186 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除