Replace a string in a textarea using selenium, “not reachable by keyboard”

前端 未结 2 1240
星月不相逢
星月不相逢 2021-01-14 05:01

I\'d like to modify part of the text in a textarea with Selenium. The textarea seems almost as if it were read-only.

In this very simple example using a sample algo,

相关标签:
2条回答
  • 2021-01-14 05:15

    Textarea has style="display: none" attribute which means that you cannot get its content with text property. In this case you can use:

    p = t.find_element_by_id('codebox').get_attribute("textContent")
    

    To set new value to code field you can use:

    field = driver.find_element_by_css_selector('div[role="presentation"]')
    driver.execute_script("arguments[0].textContent = 'New value';", field)
    

    But note that initially each code line in code field displayed as separate div node with specific value and styles. So to make new value looks exactly as code (in the same formatting) you can prepare HTML sample e.g.

    value = """<div style="position: relative;"><div class="CodeMirror-gutter-wrapper" style="left: -48px;"><div class="CodeMirror-linenumber CodeMirror-gutter-elt" style="left: 15px; width: 21px;">1</div></div><pre class=" CodeMirror-line " role="presentation"><span role="presentation" style="padding-right: 0.1px;"><span class="cm-comment"># Comment for new code.</span></span></pre></div>"""
    

    and do

    driver.execute_script("arguments[0].innerHTML = arguments[1];", field, value)
    
    0 讨论(0)
  • 2021-01-14 05:24

    The content of the algorithm with codebox which you are trying to extract is having the style attribute set to display: none;. So to extract the text you can use the following lines of code :

    p = t.find_element_by_xpath("//div[@class='ide-container']/textarea[@id='codebox']")
    t.execute_script("arguments[0].removeAttribute('style')", p)
    print(t.get_attribute("innerHTML"))
    
    0 讨论(0)
提交回复
热议问题