python - Parse Beautifulsoup output to csv file for download -
this question has answer here:
i've gone through questions on site , googled struggling take beautifulsoup output (which appear lists) , return in csv format user of flask app can download in browser. here's code:
html = col_result.__html__() bs = beautifulsoup(html) table = bs.find(lambda tag: tag.name == 'table') headers = table.findall(lambda tag: tag.name == 'th') rows = table.findall(lambda tag: tag.name == 'tr') open('export_file.csv', 'w+', newline='') f: file = csv.writer(f) file.writerow(headers) file.writerows(rows) rfile = csv.reader(open('export_file.csv', newline='')) return response( rfile, mimetype="text/csv", headers={"content-disposition": "attachment; filename=export_file.csv"})
the csv file blank when downloaded. have imported csv & bs4 modules. can advise how produce raw csv data html can passed 'rfile' variable in return response() section of code cannot work?
for example if iterate through csv.reader object , print each line get,
['firstname', 'surname', 'department', 'manager', 'absence periods', 'late instances'] ['renata', 'krzysik', 'gifts', 'michael de jäger', '0 absence', '0 lateness']...
...but cant work out how parse csv format (without lists , html tags)and assign rfile variable?
the first parameter of response
class should be
response – string or response iterable
so don't think can pass csv.reader
parameter. try pass string
content of file instead.
or can use make_response
, pass contents of csv
file it:
from flask import make_response html = col_result.__html__() bs = beautifulsoup(html) table = bs.find(lambda tag: tag.name == 'table') headers = table.findall(lambda tag: tag.name == 'th') rows = table.findall(lambda tag: tag.name == 'tr') open('export_file.csv', 'w+', newline='') f: file = csv.writer(f) file.writerow(headers) file.writerows(rows) open('export_file.csv', 'r') csv: response = make_response(csv.read()) response.headers["content-disposition"] = "attachment; filename=books.csv" return response
Comments
Post a Comment