不确定如何继续。不确定如何将数据加载到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。最后一列有注释。
发布于 2019-01-14 15:06:16
仅限于您提供的内容,我只能做一个通用的解决方案。
给定:
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)
https://stackoverflow.com/questions/54175651
复制