无法使用 openpyxl 在 excel 文件中写入 html 内容

Unable to write html content in an excel file using openpyxl

我在 python 中创建了一个小脚本,用于从网站上抓取第一个标题及其描述,并使用 openpyxl 库将其写入 excel 文件。这里要注意的重要一点是,我希望将标题保存为文本,但将描述保存为原始 html 内容,而不是文本。

我试过:

import requests
from bs4 import BeautifulSoup
from openpyxl import Workbook

link = "https://whosebug.com/questions/tagged/web-scraping"
wb = Workbook()
wb.remove(wb['Sheet'])

def fetch_content(link):
    req = requests.get(link)
    soup = BeautifulSoup(req.text,"lxml")
    title = soup.select_one("#questions .summary .question-hyperlink").get_text(strip=True)
    desc = soup.select_one("#questions .summary")

    ws.append([title,desc])
    print(title,desc)

if __name__ == '__main__':
    ws = wb.create_sheet("output")
    ws.append(['Title','Description'])
    fetch_content(link)
    wb.save("SO.xlsx")

当我 运行 脚本时,出现以下错误:

raise ValueError("Cannot convert {0!r} to Excel".format(value))
ValueError: Cannot convert <div class="summary"> -----so on

该 excel 文件中的预期输出(均 t运行):

How to scrape data   <div class="summary">

stovfl 和 robot.txt 做出了完美的解决方案。我冒昧 post 回答,因为我经常忘记这种方法。

def fetch_content(link):
    req = requests.get(link)
    soup = BeautifulSoup(req.text,"lxml")
    title = soup.select_one("#questions .summary .question-  hyperlink").get_text(strip=True)
    desc = soup.select_one("#questions .summary")

    ws.append([title,str(desc)]) #cast desc to str
    print(title,desc)