Issue
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.
Solution
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
Answered By - Shine J
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.