繁体   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