I'm trying to loop through each column of each row of data scraped from a website table to look for and remove specific sub-strings. After each column in a row has been checked and replaced if need be, the row should be appended to the CSV file.
I've tried a few different things but nothing is working. Here is my current code.
with open('Transactions.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
writer.writerow([account_name, account_number])
writer.writerow(["Date", "Details", "Debit", "Credit", "Balance"])
for row in soup.select('tr'):
text_columns = [td.a.get_text(strip=True) if td.a else td.get_text(strip=True) for td in row.select('td')]
column_array = []
for col in text_columns:
if (col.find("+$") != -1):
col.replace("+$", "")
column_array.append(col)
elif (col.find("minus$") != -1):
col.replace("minus$", "")
column_array.append(col)
else:
column_array.append(col)
writer.writerow(column_array)
The file is still produced without any of the sub-strings being removed. Please help.
Got it sorted thanks to Barmar within the comments of the original question.
Here is my current working, and simplified code.
# Writing website data to a CSV file
with open('Transactions.csv', 'w', newline='') as outfile:
writer = csv.writer(outfile)
writer.writerow([account_name, account_number])
writer.writerow(["Date", "Details", "Debit", "Credit", "Balance"])
for row in soup.select('tr'):
text_columns = [td.a.get_text(strip=True) if td.a else td.get_text(strip=True) for td in row.select('td')]
column_array = []
for col in text_columns:
str = col.replace("+$", "").replace("minus$", "")
column_array.append(str)
writer.writerow(column_array)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.