首页 > 解决方案 > 遍历所有记录,直到到达文件并输入到 sqlite

问题描述

不知道如何进行。不确定如何将数据加载到 sqlite 表中。

https://pastebin.com/wxmaNACf

#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 。最后一列有评论。

标签: python-3.xbeautifulsoup

解决方案


仅限于您提供的内容,我只能做一个通用的解决方案。

鉴于:

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)

推荐阅读