I am scraping some data using BeautifulSoup and want to write it into an excel file. But for some reason only the last iteration gets written in the excel file. My Code:
import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook, workbook
from openpyxl.utils import get_column_letter
import itertools
html_text = requests.get("https://medex.com.bd/brands").text
soup = BeautifulSoup(html_text, 'lxml')
boxes = soup.find_all('div', class_='row data-row')
number = 1
for box in boxes:
contents = box.find_all('div', class_='col-xs-12')
workbook = Workbook()
sheet = workbook.active
for (content, alphabet) in zip(contents, range(1,6)):
char = get_column_letter(alphabet)
sheet[f"{char}{str(number)}"] = content.text.strip()
print(content.text.strip())
number+=1
workbook.save(filename='trial.xlsx')
Define the following codes outside the for loop
workbook = Workbook()
sheet = workbook.active
import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook, workbook
from openpyxl.utils import get_column_letter
import itertools
html_text = requests.get("https://medex.com.bd/brands").text
soup = BeautifulSoup(html_text, 'lxml')
boxes = soup.find_all('div', class_='row data-row')
number = 1
workbook = Workbook()
sheet = workbook.active
for box in boxes:
contents = box.find_all('div', class_='col-xs-12')
for (content, alphabet) in zip(contents, range(1,6)):
char = get_column_letter(alphabet)
sheet[f"{char}{str(number)}"] = content.text.strip()
# sheet[f"{char}{str(number)}"].append(content.text.strip())
# sheet.append([f"{char}{str(number)}"] = content.text.strip())
print(content.text.strip())
number+=1
workbook.save(filename='trial.xlsx')
[Solved]
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.