I'm trying to export data to an excel file. any help would be appreciated I keep running into errors.
The data that code is pulling and I want to export to excel:
[{'Date': '07/01/2022 '}]
my attempt I'm trying to export to excel:
soup = BeautifulSoup(driver.page_source,'html.parser')
data = [{
'Date':soup.select_one('li.list-group-item .text-primary').text.strip()#.replace(' Date','')
}]
print (data)
datatoexcel = pd.ExcelWriter('Dates.xlsx')
data.to_excel(datatoexcel)
datatoexcel.save()
print('DataFrame is Written to Excel Successfully.')
This error is popping up
data.to_excel AttributeError: 'list' object has no attribute 'to_excel'
I've also tried this
soup = BeautifulSoup(driver.page_source,'html.parser')
data = [{
'Date':soup.select_one('li.list-group-item .text-primary').text.strip()#.replace(' Date','')
}]
print (data)
new_df = pd.dataframe(data)
new_df.head()
error
AttributeError: module 'pandas' has no attribute 'dataframe'
can someone explain what I'm doing wrong?
CodePudding user response:
You are getting AttributeError: module 'pandas' has no attribute 'dataframe'
because dataframe spell should be as follows:
df=pd.DataFrame(data)
Once this is corrected try to export it to excel using to_excel
:
df.to_excel('filename.xlsx')
CodePudding user response:
I think you can use openpyxl library for this purpose. You can create a function using following:
def XLSExport(Rows, SheetName, FileName):
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = SheetName
# ws = wb.create_sheet(SheetName)
for x in Rows:
ws.append(x)
wb.save(FileName)
You can collect the data to be written in an excel with following format:
ExcelExport.append([ip,card_elo['Card_ID'],card_elo['Card_Detail']['Part_Number'],card_elo['Card_Detail']['Serial_Number']])
as a last step, following help you to have your data into an excel file.
XLSExport(ExcelExport, "INFORMATION", "PART_SERIAL_NUMBERS.xlsx")
CodePudding user response:
You only need the ExcelWriter if you need a wrapper for the file you are writing to, e.g. if you want to save multiple DataFrames to multiple sheets.
For a basic case like yours you can just directly write the DataFrame to Excel. However what you created is a list of dictionaries and not a DataFrame. So you need to convert it to a DataFrame first. I assume you mean that this list can contain any number of such dicts.
import pandas
soup = BeautifulSoup(driver.page_source,'html.parser')
data = [{
'Date':soup.select_one('li.list-group-item .text-primary').text.strip()
}]
df = pandas.DataFrame(data)
df.to_excel("Dates.xlsx")
print('DataFrame is Written to Excel Successfully.')