【问题标题】:Reading each line of HTML table into python list将HTML表格的每一行读入python列表
【发布时间】:2019-02-19 20:38:15
【问题描述】:

我正在尝试使用 python 抓取 HTML 表格。我正在用漂亮的汤来做这个网页抓取。 HTML 页面中有很多表格,表格中有很多行。我希望每一行都有不同的名称,如果行中有列,希望它们是分开的。

我的代码如下所示:

page = get("https://www.4dpredict.com/mysingaporetoto.p3.html")
html = BeautifulSoup(page.content, 'html.parser')
result = defaultdict(list)
tables = html.find_all('table')
for table in tables:
    for row in table.find_all('tr')[0:15]:
        try:
            #stuck here
        except ValueError:
            continue  # blank/empty row

需要一些指导。

【问题讨论】:

    标签: python html web-scraping


    【解决方案1】:

    请检查以下代码,如果不起作用,请告诉我,

    import requests
    from bs4 import BeautifulSoup
    import pprint
    page = requests.get("https://www.4dpredict.com/mysingaporetoto.p3.html")
    html = BeautifulSoup(page.content, 'html.parser')
    
    tables = html.find_all('table')
    table_data = dict()
    for table_id, table in enumerate(tables):
        print('[!] Scraping Table -', table_id + 1)
        table_data['table_{}'.format(table_id+1)] = dict()
        table_info = table_data['table_{}'.format(table_id+1)]
        for row_id, row in enumerate(table.find_all('tr')):
            col = []
            for val in row.find_all('td'):
                val = val.text
                val = val.replace('\n', '').strip()
                if val:
                    col.append(val)
            table_info['row_{}'.format(row_id+1)] = col
        pprint.pprint(table_info)
        print('+-+' * 20)
    
    pprint.pprint(table_data)
    

    样本输出

    [!] Scraping Table - 1
    {'row_1': ['SINGAPORE TOTO2018-08-23 (Thu) 3399'],
     'row_10': ['Group 2', '$', '-'],
     'row_11': ['Group 3', '$1,614', '124'],
     'row_12': ['Group 4', '$344', '318'],
     'row_13': ['Group 5', '$50', '6,876'],
     'row_14': ['Group 6', '$25', '9,092'],
     'row_15': ['Group 7', '$10', '117,080'],
     'row_16': ['SHOW ANALYSISEVEN : ODD, 2 : 5SUM :138, AVERAGE :23 MIN :02, MAX '
                ':41, DIFF :39',
                'EVEN : ODD, 2 : 5',
                'SUM :138, AVERAGE :23',
                'MIN :02, MAX :41, DIFF :39'],
     'row_17': ['EVEN : ODD, 2 : 5'],
     'row_18': ['SUM :138, AVERAGE :23'],
     'row_19': ['MIN :02, MAX :41, DIFF :39'],
     'row_2': ['WINNING NUMBERS'],
     'row_3': ['02', '03', '23', '30', '39', '41'],
     'row_4': ['ADDITIONAL'],
     'row_5': ['19'],
     'row_6': ['Prize: $2,499,788'],
     'row_7': ['WINNING SHARES'],
     'row_8': ['Group', 'Share Amt', 'Winners'],
     'row_9': ['Group 1', '$1,249,894', '2']}
    +-++-++-++-++-++-++-++-++-++-++-++-++-++-++-++-++-++-++-++-+
    

    【讨论】:

      【解决方案2】:

      如果我正确理解了您的要求,以下脚本应该可以解决问题:

      import requests
      from bs4 import BeautifulSoup
      
      url = 'https://www.4dpredict.com/mysingaporetoto.p3.html'
      
      res = requests.get(url).text
      soup = BeautifulSoup(res, 'lxml')
      num = 0
      for tables in soup.select("table tr"):
          num+=1
          data = [f'{num}'] + [item.get_text(strip=True) for item in tables.select("td")]
          print(data)
      

      部分输出:

      ['1', 'SINGAPORE TOTO2018-08-23 (Thu) 3399']
      ['2', 'WINNING NUMBERS']
      ['3', '02', '03', '23', '30', '39', '41']
      ['4', 'ADDITIONAL']
      ['5', '19']
      ['6', 'Prize:$2,499,788']
      ['7', 'WINNING SHARES']
      ['8', 'Group', 'Share Amt', 'Winners']
      ['9', 'Group 1', '$1,249,894', '2']
      ['10', 'Group 2', '$', '-']
      ['11', 'Group 3', '$1,614', '124']
      ['12', 'Group 4', '$344', '318']
      ['13', 'Group 5', '$50', '6,876']
      ['14', 'Group 6', '$25', '9,092']
      

      【讨论】:

      • 如果你使用的是python的最新版本,我怀疑有什么错误。查看脚本产生的输出。
      • 如何解决这个问题?
      • 试试这个['%s' % num]替换[f'{num}']
      • 那我没能理解你的要求。谢谢。
      【解决方案3】:

      我会建议使用 requests.get() 而不是 get() 方法

      【讨论】:

      • 能否请您使用一些 OP 代码来增强您的答案?明确哪行代码将是 OP 问题的答案。
      • OP 似乎使用了requests 库。然而,他可能从它导入了get,就像from requests import get一样。我仍然找不到问题的答案与您的 oneliner 评论之间的任何关联..
      • 感谢 SIM 的建议。我是 python 的新手,也是堆栈溢出的新手。尝试学习和解决..
      【解决方案4】:

      我建议放弃 BeautifulSoup(尽管它很漂亮)并使用 pandas(在后端使用 BeautifulSoup 或 lxml)。您所描述的是熊猫的沼泽标准,只需阅读文档即可。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-03
        • 1970-01-01
        • 2017-11-20
        • 1970-01-01
        • 2023-03-03
        • 2022-11-10
        • 1970-01-01
        相关资源
        最近更新 更多