python-3.x - 遍历所有记录,直到到达文件并输入到 sqlite
问题描述
不知道如何进行。不确定如何将数据加载到 sqlite 表中。
#create sqllite engine
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=True)
#load results to soup
from bs4 import BeautifulSoup
soup = BeautifulSoup(r.content, 'html.parser')
#iterate through. How do I load the data parsed into the data table.
for td_tag in soup.find_all('td'):
print(td_tag.text, td_tag.next_sibling)
context = (td_tag.text)
需要有一个 5 列的 sqlite 表。第一列是公司名称,第二列是按地区划分的日期,没有分隔符,即北美 2019 年 4 月 欧洲 2019 年 5 月 亚洲 2019 年 10 月。第三列是评论。第四列有链接的文本,即 iPhone 6S 。最后一列有评论。
解决方案
仅限于您提供的内容,我只能做一个通用的解决方案。
鉴于:
html = '''
<tr>
<td style="min-width: 5px; width: 150px; text-align: left;">
<strong>
Apple
</strong>
</td>
<td style="min-width: 5px; width: 290px;">
<div align="center" style="text-align: left;">
April 1, 2020
</div>
</td>
<td style="min-width: 5px; width: 48px; text-align: center;">
<div align="center"></div>
</td>
<td style="min-width: 5px; width: 133px; text-align: center;">
<div align="center"></div>
</td>
<td style="min-width: 5px; width: 437px;">
Blah1, blah2
</td>
</tr>'''
然后你会有类似的东西:
import pandas as pd
import bs4
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=True)
soup = bs4.BeautifulSoup(html, 'html.parser')
df = pd.DataFrame()
rows = soup.find_all('tr')
for row in rows:
td = row.find_all('td')
data_list = [ data.text.strip() for data in td ]
temp_df = pd.DataFrame([data_list])
df = df.append(temp_df)
df.reset_index(drop=True)
df.to_sql('new_table', con=engine)
推荐阅读
- javascript - 有没有办法改变元素的默认吸气剂?
- apache - 我可以从本地设备连接到 apache 服务器,但不能从互联网连接
- ios - Unity Facebook SDK & iOS 14.5:登录未命中的理解
- postgresql - 我的 postgresql 查询有什么问题,为什么我没有得到正确的计算
- next.js - Aws amplify nextjs 应用程序构建失败,没有错误日志
- c++ - OpenCV 中的 Cholesky 分解
- cypher - 如何对简单校验和进行逆向工程
- python - 训练多个 Keras 模型可增加 RAM
- java - 如何更改 webview android 中下拉菜单的背景颜色?
- android - 从 android studio 调试中运行的应用程序是否注册意图。尝试从 NFC 标签启动