小弟是新學Python 而且拼了個小程式.但是想進一步將資料寫到EXCEL 就是不成功.
試了openpyxl , xlwings ,xlsxwriter 都沒有成功,
請各位先進指導一下可以嗎?
我想將資料一行一行寫入到EXCEL.
from selenium import webdriver
from bs4 import BeautifulSoup
chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_argument('--headless')
chromeOptions.add_argument('--disable-gpu')
chromeOptions.add_argument('--disable-dev-shm-usage')
chromeOptions.add_argument('--no-sandbox')
driver = webdriver.Chrome(chrome_options=chromeOptions,executable_path="/usr/bin/chromedriver")
driver.get('https://stock360.hkej.com/indices/futures')
pageSource = driver.page_source
soup = BeautifulSoup(pageSource, 'html.parser')
#data = soup.find_all(name='td',attrs={"class":"ng-binding"})
data = soup.select('#TB_HSIF1 td')
# get the index price
for i in data: print(i.text)
以下是錯的示範
from selenium import webdriver
from bs4 import BeautifulSoup
import datetime
from openpyxl import Workbook
chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_argument('--headless')
chromeOptions.add_argument('--disable-gpu')
chromeOptions.add_argument('--disable-dev-shm-usage')
chromeOptions.add_argument('--no-sandbox')
driver = webdriver.Chrome(chrome_options=chromeOptions,executable_path="/usr/bin/chromedriver")
driver.get('https://stock360.hkej.com/indices/futures')
pageSource = driver.page_source
soup = BeautifulSoup(pageSource, 'html.parser')
#data = soup.find_all(name='td',attrs={"class":"ng-binding"})
data = soup.select('#TB_HSIF1 td')
# get the index price
#for i in data: print(i.text)
# write to excel
wb = Workbook()
sheet = wb.active
for i in data:
sheet["A%d" % (i+1)].value = i + 1
wb.save('test.xlsx')
driver.quit()
Traceback (most recent call last):
File "test3.2.py", line 32, in
sheet["A%d" % (i+1)].value = i + 1
TypeError: unsupported operand type(s) for +: 'Tag' and 'int'
你debug訊息很明顯告訴你了:
Traceback (most recent call last):
File "test3.2.py", line 32, in
sheet["A%d" % (i+1)].value = i + 1 # 錯在這行
TypeError: unsupported operand type(s) for +: 'Tag' and 'int'
i是BeautifulSoup的 Tag 物件,沒辦法和 1 這個int相加
寫程式最重要是會看debug。