【问题标题】:How can I parse rows in a table that are composed of cells that aren't just <td> but an occasional <th> cell?如何解析表中由不只是 <td> 而是偶尔的 <th> 单元格的单元格组成的行?
【发布时间】:2019-05-01 14:17:45
【问题描述】:

我对@9​​87654321@ 还是很陌生,对BeautifulSoup 还是很陌生。我一直在努力使用BeautifulSoup 创建一个网络爬虫,以进入并解析网站上的部门目录。这些目录在 HTML 表中结构化。正如预期的那样,大多数单元格都是td 标签;但是,偶尔有一个单元格是 th 标记,我也需要对其进行解析。

这些页面中的大多数是.aspx,我读到要抓取这些页面,需要 Web 驱动程序。这是我的初始代码,我主要将 BeautifulSoup 用于请求,所以我不确定将其与 Web 驱动程序一起使用是否正确。

url = "https://webberathletics.com/staff.aspx"
driver = webdriver.Chrome(r"C:\Users\bobby\OneDrive\Documents\MyPrograms\webdrivers\chromedriver.exe")
driver.implicitly_wait(30)
driver.get(url)

soup = BeautifulSoup(driver.page_source, 'html.parser')
contacts_list = []

我将添加更多 URL 供抓取器解析,因此我试图使抓取器尽可能动态,这意味着它将抓取包含具有 th 单元格的行和其他不包含的行的表不。以下是我目前拥有的。

我希望它解析单元格是td 还是th

for row in soup.find_all('tr'):
    cells = row.find_all('td', 'th')

    if len(cells) > 0:
        col1 = cells[0].text.strip()
        col2 = cells[1].text.strip()
        col3 = cells[2].text.strip()
        col4 = cells[3].text.strip()

        contact = {'col1': col1, 'col2': col2, 'col3': col3, 'col4': col4}
        contacts_list.append(contact)

        print(contacts_list)

目前它根本不会打印,但它会运行,所以我不确定它是否正常工作。但即使它确实打印了,我也不确定我是否正确地处理了这个问题。

【问题讨论】:

    标签: python html parsing html-table beautifulsoup


    【解决方案1】:

    如果您要使用 &lt;table&gt; 标签抓取表格,我会选择只使用 Pandas .read_html()。辛苦了么。

    from selenium import webdriver
    import pandas as pd
    
    
    url = "https://webberathletics.com/staff.aspx"
    driver = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe')
    driver.implicitly_wait(30)
    driver.get(url)
    
    tables = pd.read_html(driver.page_source)
    df = tables[1]
    df = df[pd.isnull(df['Image'])].drop(['Image'], axis=1)
    
    driver.close()
    

    输出:

    print (df)
    

    编辑:

    如果你想保留那些“副标题”:

    from selenium import webdriver
    import pandas as pd
    
    
    url = "https://webberathletics.com/staff.aspx"
    driver = webdriver.Chrome('C:/chromedriver_win32/chromedriver.exe')
    driver.implicitly_wait(30)
    driver.get(url)
    
    tables = pd.read_html(driver.page_source)
    df = tables[1]
    

    【讨论】:

    • 感谢您的回复!它工作得很好,我现在遇到的唯一挑战是我之前没有提到的,因为我正在解析整个表格是划分表格的部门标题。我需要将这些包含在解析中,以便在格式化数据时知道谁在哪个部门。有没有办法将其添加为字段或列?
    • 这些部门不是也在他们的头衔中吗?
    • 您可以将这些包含在表格中,这只是让它有点乱。所以你必须做一些清理工作。但我在编辑的解决方案中添加了这一点
    • 不,他们不是,在这种情况下,对于这个特定的网站,他们是,但如果我继续使用运动目录,有些人只会说 head coach 而没有注意到这项运动,所以我需要了解部门以了解他们执教的运动。
    • 啊,明白了。酷。
    猜你喜欢
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 2010-12-26
    • 1970-01-01
    • 2013-01-16
    • 2012-06-14
    相关资源
    最近更新 更多