Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can we replace a character from an elemnt after we took it by xpath with selenium in pthon?

I want to get the text of an element from xpath with selenium in python. after I get the text go to the condition and find if it is an special character here "-"replace it with "0". however all the time I get an error.

quantities = driver.find_element(By.XPATH,f'./html/body/table/tbody/tr/td/table/tbody/tr/td/form/table/tbody/tr/td/table[4]/tbody/tr/td/table/tbody/tr/td/table[1]/tbody/tr/td/table/tbody/tr[{row}]/td[7]'.format())
if str(quantities.text)=="-":
      (quantities.text)=(quantities.text).replace('-','0')
SKorea_Result.append(str(SKorea_Start_Year)+','+str(SKorea_Start_Month)+','+'1'+','+str(my_Skorea_Hscode[j])+','+str(countries.text)+','+(str(quantities.text)).replace(',',''))

The error belongs to the 3rd line is :
can’t set attribute ‘text’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You cannot change the text of the element. You can save the text of that element in a variable and use replace() on that.
So:

quantities = driver.find_element(By.XPATH,f'./html/body/table/tbody/tr/td/table/tbody/tr/td/form/table/tbody/tr/td/table[4]/tbody/tr/td/table/tbody/tr/td/table[1]/tbody/tr/td/table/tbody/tr[{row}]/td[7]'.format())
# I don't think it's needed to cast to str(), text should already be a string.
text_variable = quantities.text
if text_variable == "-":
    text_variable=text_variable.replace('-', '0')
SKorea_Result.append(str(SKorea_Start_Year)+','+str(SKorea_Start_Month)+','+'1'+','+str(my_Skorea_Hscode[j])+','+str(countries.text)+','+(str(quantities.text)).replace(',',''))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use