Home > Back-end >  How can modify text in table as python selenium?
How can modify text in table as python selenium?

Time:04-03

I'm crawling with python3 and selenium.
I want to modify text in table

<table >
  <tbody>
    <tr>...</tr>
    <tr>
      <td>
        <center>
          This is text
        </center>
      </td>
    </tr>
    <tr>...</tr>
  </tbody>
</table>

My goal is to modify "This is text" to another text. I tried below code.

# python3   selenium

table = driver.find_element_by_xpath("table xpath")

for tr in table.find_elements(By.TAG_NAME, 'tr'):
    for td in tr.find_elements(By.TAG_NAME, 'td'):
        for target in td.find_elements(By.TAG_NAME, 'center'):
            print(target.text) # This is text
            driver.execute_script('document.getElementById("{}").innerHTML = {}";"'.format(target, "new text"))
        

I got the following error

selenium.common.exceptions.JavascriptException: Message: javascript error: Unexpected identifier
  (Session info: headless chrome=100.0.4896.60)

How can modify that?
Thank you.

CodePudding user response:

The document.getElementById expects an ID and not a WebElement. You're trying to pass a WebElement to it.

Do this instead:

table = driver.find_element(By.XPATH,'//table[@]')
new_text = "This is the new text"

for tr in table.find_elements(By.TAG_NAME, 'tr'):
    for td in tr.find_elements(By.TAG_NAME, 'td'):
        for target in td.find_elements(By.TAG_NAME, 'center'):
            print(f'Text before: {target.text}')
            driver.execute_script(f'arguments[0].innerHTML="{new_text}"', target)
            print(f'Text after: {target.text}\n')

For more information about arguments[0] in execute_script, read this answer What does arguments0 and arguments1 mean

CodePudding user response:

This Error comes from javascript that you are passing an incorrect element ID to execute the DOM element to change the text.

You should use either document.getElementsByTagNameNS() or document.getElementsByTagName() which would return a list that you could control it by javascript for loop to loop through each elements with the same tag name you passed into the script to modify it.

Or you could just pass in the correct ID into document.getElementByID()

  • Related