【问题标题】:Can't write tabular content in an excel file using pandas ExcelWriter无法使用 pandas ExcelWriter 在 excel 文件中写入表格内容
【发布时间】:2019-06-29 22:24:30
【问题描述】:

我创建了一个 python 脚本来从网页中获取一些表格内容,并使用 pandas ExcelWriter 将其写入 excel 文件中。表格数据正确通过,但我无法将它们写入 excel 文件。我可以使用openpyxl 编写相同的内容,但对于熊猫ExcelWriter,我会卡住。

我试过了:

import requests
import pandas as pd
from bs4 import BeautifulSoup
from pandas import ExcelWriter

link = "https://en.wikipedia.org/wiki/Comparison_of_Intel_processors"
result = []

res = requests.get(link)
soup = BeautifulSoup(res.text,"lxml")
for items in soup.select_one("table.wikitable").select("tr"):
    data = [item.get_text(strip=True) for item in items.select("th,td")]
    print(data)
    result+=data

df = pd.DataFrame(result)
writer = ExcelWriter('tabular_content.xlsx')
df.to_excel(writer,'Sheet1',index=False)
writer.save()

为了避免混淆我得到什么和我希望得到什么,我给出了两个例子来描述图片。

我目前的方法可以将数据写入单个列中,如下所示。

Processor
SeriesNomenclature
CodeName
Production Date
Supported Features (Instruction Set)
Clock Rate
Socket
Fabri-cation

但是,我希望将它们写成如下:

Processor   SeriesNomenclature  CodeName    Production Date Supported Features (Instruction Set)
4004            Nov. 15,1971    
8008    N/A N/A April 1972  N/A
8080    N/A N/A April 1974  N/A
8085    N/A N/A March 1976  N/A
8086    N/A N/A June 8, 1978    N/A
8088    N/A N/A June 1979   N/A
80286   N/A N/A Feb. 1982   N/A
i80386  DX, SX, SL  N/A 1985 - 1990 N/A
i80486  DX, SX, DX2, DX4, SL    N/A 1989 - 1992 N/A

附:必须使用ExcelWriter

【问题讨论】:

    标签: python python-3.x pandas web-scraping beautifulsoup


    【解决方案1】:

    ExcelWriter 似乎没有问题,在这种情况下,您甚至不需要 BeautifulSoup。只需这样读取数据

        tables = pd.read_html("https://en.wikipedia.org/wiki/Comparison_of_Intel_processors")
    
        writer = ExcelWriter('tabular_content.xlsx')
        tables[0].to_excel(writer,'Sheet1',index=False)
        writer.save()
    

    而且,至少在我的系统上,它按预期创建了 Excel 文件。

    【讨论】:

    • 感谢您的回答@Jack Fleeting。我熟悉pd.read_html(),但我不希望那样做,这就是我使用 BeautifulSoup 的原因。
    猜你喜欢
    • 2021-06-06
    • 2021-07-26
    • 2015-03-19
    • 1970-01-01
    • 2021-07-27
    • 2022-12-12
    • 2017-06-24
    • 1970-01-01
    • 2017-03-30
    相关资源
    最近更新 更多