KSH
KSH

Reputation: 3

How can modify text in table as python selenium?

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

<table class="my 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.

Upvotes: 0

Views: 185

Answers (1)

Shine J
Shine J

Reputation: 818

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[@class="my 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

Upvotes: 1

Related Questions