【问题标题】:How do you export python data to excel using xlwt?如何使用 xlwt 将 python 数据导出到 excel?
【发布时间】:2018-08-13 07:11:32
【问题描述】:

这是我的总结:

from bs4 import BeautifulSoup
import requests

url = 'http://www.baseballpress.com/lineups'

soup = BeautifulSoup(requests.get(url).text, 'html.parser')

for names in soup.find_all(class_="players"):
    print(names.text) 

我想使用 xlwt 将我的抓取导入到 excel 中。我使用下面的代码来查看是否可以使用 python 制作一个 excel 表:

import xlwt  

wb = xlwt.Workbook()  
ws = wb.add_sheet("Batters")  
ws.write(0,0,"coding isn't easy")  
wb.save("myfirst_xlwt")

上面的代码有效。我现在想把它应用到我原来的刮。如何合并这两个代码?

我是新手,因此我们将不胜感激。谢谢你的时间! =)

【问题讨论】:

  • 我这里没有xlwt但是你可以试试this教程
  • 感谢@Nullman!

标签: python web-scraping beautifulsoup request xlwt


【解决方案1】:

我尝试运行您的代码,但找不到任何具有 example 类的内容。它返回[]

关于xlwt,基本上,它只是使用您指定的字符串写入一个单元格(带有行和列参数)。

wb = xlwt.Workbook() 
ws = wb.add_sheet('sheet_name')
ws.write(0,0,"content") #Writes the first row, first col, in sheet called "sheet_name".
wb.save("example.xls")  

但是,我认为pandas 更适合此目的。如果您忘记了行号和列号,xlwt 有时会变得非常混乱。如果您可以提供一些非空结果,我可以为您编写一个简单的脚本,以使用 pandas 导出到 Excel。

为了在您的示例中使用pandas,这里是代码。

from bs4 import BeautifulSoup
import requests

url = 'http://www.baseballpress.com/lineups'

soup = BeautifulSoup(requests.get(url).text, 'html.parser')

all_games = []

for g in soup.find_all(class_="game"):
    players = g.find_all('a', class_='player-link')
    game = {
        'time': g.find(class_='game-time').text,
        'weather': g.find(target='forecast').text.strip(),
        'players': [_.text for _ in g.find_all('a', class_='player-link')],
    }
    all_games.append(game)

print(all_games) # This will print out a list of dict that contains the game information

import pandas as pd
df = pd.DataFrame.from_dict(all_games) # Construct dataframe from the list of dict
writer = pd.ExcelWriter('baseball.xlsx') # Init Pandas excel writer, using the file name 'baseball.xlsx'
df.to_excel(writer, 'baseball_sheet') # Writes to a sheet called 'baseball_sheet'. Format follows the Dataframe format.
writer.save() # Save excel

【讨论】:

  • 当然 :) 如果您能接受答案,那就太好了
  • 我再次调整了代码@MartinLiu ...我不确定这是否是您想要的。你能进一步解释你的问题吗?再次感谢 =) 我将不得不考虑使用熊猫。
  • 编辑了我的代码。如果您只想将所有内容导出到 Excel,Pandas 会更简单。您需要做的就是构建一个字典列表,然后将其转换为 pandas DataFrame。
  • 很高兴为您提供帮助。编辑了我的代码。是的,网站结构非常简单,您需要做的就是找到标签(在本例中为 ),以及一些识别它的方法(所有玩家都有“玩家链接”的class)跨度>
  • 也许在使用 Python shell 时尝试查找您所在的目录?或者你可以在writer = pd.ExcelWriter('baseball.xlsx')中添加绝对路径。
【解决方案2】:

合并sn-ps 的最简单方法是在任何有print 语句的地方使用ws.write。您可以使用enumerate 来跟踪您的行索引:

from bs4 import BeautifulSoup
import requests
import xlwt  

wb = xlwt.Workbook()  
ws = wb.add_sheet("Batters")  

url = 'http://www.baseballpress.com/lineups'

soup = BeautifulSoup(requests.get(url).text, 'html.parser')

for row, name in enumerate(soup.find_all(class_="players")):
    ws.write(row, 0, name.text)
wb.save("myfirst_xlwt")

【讨论】:

  • 泰!!! @MadPhysicist =) 我非常感谢您的反馈。我会尽快测试...
  • Traceback(最近一次调用最后一次):文件“C:/Users/xboss/Desktop/Baseball_Sheet_Code.py”,第 12 行,在 中为行,名称在 soup.find_all(class_= "players"): ValueError: no enough values to unpack (expected 2, got 0)
  • 知道为什么我会收到@MadPhysicist 的错误吗?抱歉...我是初学者。
  • 因为我忘了像我宣传的那样添加enumerate。我的错。现已修复。
  • 感谢您抽出宝贵时间!我非常感谢您的帮助。 =)
猜你喜欢
  • 1970-01-01
  • 2021-11-14
  • 2018-10-30
  • 1970-01-01
  • 1970-01-01
  • 2015-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多