簡體   English   中英

Python openpyxl 只寫最后一次迭代

[英]Python openpyxl writes only the last iteration

我正在使用 BeautifulSoup 抓取一些數據,並希望將其寫入 excel 文件。 但由於某種原因,只有最后一次迭代被寫入 excel 文件中。 我的代碼:

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

在for循環外定義以下代碼

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

[解決了]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM