Home > Back-end >  How can we replace a character from an elemnt after we took it by xpath with selenium in pthon?
How can we replace a character from an elemnt after we took it by xpath with selenium in pthon?

Time:09-20

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'

CodePudding user response:

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(',',''))

CodePudding user response:

You can only change the text if the element is text field or input element:

text = quantities.text
if '-' in text:
    new_text = new_text.replace('-', '0')
    quantities.clear()
    quantities.send_keys(new_text)

This won't work if the text you are reading is a div or a span

  • Related