python - 将对象列表到 DataFrame 到 Azure 上的 MySQL DB
问题描述
我使用 Selenium 和 Pandas 从网站上抓取一个表格,生成一个列表对象。然后我尝试将列表转换为 DataFrame 以将其写入 MySQL。
当我打印我的抓取结果时,它是一个很好的表格格式,具有清晰的行号和列标题,但是当我执行“len”时,结果为 1。
我已经尝试了很多方法,并且真的可以使用一些帮助。
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#import csv
from bs4 import BeautifulSoup
import pandas as pd
from pandas import DataFrame
import time
from sqlalchemy import create_engine
# base url
baseurl = "https://bitcoincharts.com/charts/bitstampUSD#igDailyztgSzm1g10zm2g25zv"
# selenium arguments
options = Options()
options.add_experimental_option("excludeSwitches", ["enable-logging"])
options.headless = True
options.add_argument("--window-size=1920,1200")
driver = webdriver.Chrome(options=options, executable_path="C:/Users/mande/OneDrive/Knowledge/Python/chromedriver.exe")
# navigates to website
driver.get(baseurl)
# clicks "show raw data"
rawdata = driver.find_element_by_xpath("/html/body/div[5]/div/div[2]/a").click()
print("Sleeping 10 seconds")
time.sleep(10)
print("Continue")
soup = BeautifulSoup(driver.page_source, 'lxml')
tables = soup.find(id='chart_table')
df = pd.read_html(str(tables), header=0)
print(df[0])
driver.quit()
print(type(df))
print(len(df))
df2 = pd.DataFrame([df])
df2.columns = ['Rownumber', 'Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume (BTC)', 'Volume (USD)', 'Weighted Price']
engine = create_engine("mysql+pymysql://user:password@hostname/dbname"
.format(user="user",
pw="password",
db="dbname"))
DataFrame.to_sql(df2, name='bitcoin', con = engine, if_exists='append', chunksize=10000, index=False)
console:
ValueError: Length mismatch: Expected axis has 1 element, new values have 9 elements
解决方案
替换这两行:
df2 = pd.DataFrame([df])
df2.columns = ['Rownumber', 'Timestamp', 'Open', 'High', 'Low', 'Close', 'Volume (BTC)', 'Volume (USD)', 'Weighted Price']
和
df2 = df[0]
为我修复它。
推荐阅读
- javascript - jQuery - 在 Range Track 上更改 CSS
- java - 如何创建一个最小的 Android gradle 项目?
- sql-server - 如何在VS中以调试模式在脚本任务中执行打包任务
- sql - PostgreSQL,在另一个表中创建行时向表中添加行
- django - 将excel文档上传到React并存储在数据库中
- css - Ionic 5 ion-tab-bar 渐变背景
- spring-kafka - 如果生产者应用程序在发送到代理之前崩溃,生产者“buffer.memory”中的消息会发生什么?
- c++ - 如何在 C++ 中将浮点数转换为无符号整数?
- java - 如何使用 Jackson 的 ObjectMapper 从 JSON 字符串创建对象?
- apache-spark - Pyspark 中的表格显示来自 CSV 文件的标题