【问题标题】:BeautifulSoup4 Returning Empty List when Attempting to Scrape a TableBeautifulSoup4 在尝试刮表时返回空列表
【发布时间】:2017-11-06 18:51:25
【问题描述】:

我正在尝试从该 url 中提取数据:https://www.winstonslab.com/players/player.php?id=98,当我尝试访问这些表时,我不断收到相同的错误。

我的抓取代码如下。我运行它,然后 hp = HTMLTableParser()table = hp.parse_url('https://www.winstonslab.com/players/player.php?id=98')[0][1] 返回错误“索引 0 超出轴 0 大小为 0 的范围”

import requests
import pandas as pd
from bs4 import BeautifulSoup

class HTMLTableParser:

    def parse_url(self, url):
        response = requests.get(url)
        soup = BeautifulSoup(response.text, 'lxml')
        return [(table['id'],self.parse_html_table(table))\
                for table in soup.find_all('table')]  

    def parse_html_table(self, table):
        n_columns = 0
        n_rows=0
        column_names = []

        # Find number of rows and columns
        # we also find the column titles if we can
        for row in table.find_all('tr'):

            # Determine the number of rows in the table
            td_tags = row.find_all('td')
            if len(td_tags) > 0:
                n_rows+=1
                if n_columns == 0:
                    # Set the number of columns for our table
                    n_columns = len(td_tags)

                # Handle column names if we find them
                th_tags = row.find_all('th') 
                if len(th_tags) > 0 and len(column_names) == 0:
                    for th in th_tags:
                        column_names.append(th.get_text())

            # Safeguard on Column Titles
            if len(column_names) > 0 and len(column_names) != n_columns:
                raise Exception("Column titles do not match the number of columns")

            columns = column_names if len(column_names) > 0 else range(0,n_columns)
            df = pd.DataFrame(columns = columns,
                          index= range(0,n_rows))
            row_marker = 0
            for row in table.find_all('tr'):
                column_marker = 0
                columns = row.find_all('td')
                for column in columns:
                    df.iat[row_marker,column_marker] = column.get_text()
                    column_marker += 1
                if len(columns) > 0:
                    row_marker += 1

            # Convert to float if possible
            for col in df:
                try:
                    df[col] = df[col].astype(float)
                except ValueError:
                    pass

            return df

【问题讨论】:

    标签: python-3.x pandas beautifulsoup


    【解决方案1】:

    如果您需要的数据只是表格,您可以使用pandas.read_html() 函数来完成。

    【讨论】:

    • 您需要查看函数中可用的参数和HTML结构。尝试一下,看看您是否可以读取丢失的数据。
    猜你喜欢
    • 2019-08-03
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多