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