忽略 BeautifulSoup 中 table 的单元格 class

Ignoring a table's cell class in BeautifulSoup

我正在从 this 网站上抓取数据以创建一个 table。我计划创建一个函数来遍历每个主题,但首先只测试会计和财务。到目前为止,我有以下代码:

import os
import requests
from bs4 import BeautifulSoup
import pandas as pd

main_url = 'http://www.thecompleteuniversityguide.co.uk/league-tables/rankings?s=Accounting+%26+Finance'

with requests.Session() as s:
    r = s.get(main_url)

    soup = BeautifulSoup(r.text, 'html5lib')
    title = soup.find('h2').contents[0]
    title = " ".join(title.split())
    table = soup.find('table', {'class': 'leagueTable hoverHighlight narrow'})
    headers = []
    rows = []
    for row in table.findAll('tr'):
        for item in row.findAll('th'):
            for link in item.findAll('a', text=True):
                headers.append(link.contents[0])

        cols = row.find_all('td')
        cols = [ele.text.strip() for ele in cols]
        rows.append(cols)

        for idx, i in enumerate(headers):
            if 'Click' in i:
                del headers[idx]
        for idx, i in enumerate(headers):
            if '2016' in i:
                del headers[idx]

    print headers
    print rows

哪个returns

[u'CUG Rank ', u'University Name ', u'Entry Standards', u'Student Satisfaction', u'Research Quality', u'Graduate Prospects', u'Overall Score']
[u'1', u'2', u'Strathclyde', u'517', u'', u'4.14', u'', u'3.17', u'', u'81', u'', u'100.0']

我将在第二个索引中插入一个额外的 header 来说明 2015 年的列,所以这不是问题,但问题出在

td class="quintile detailColumn"

因为这些 returns 每个值后都有一个空值(这些是每个度量下的条形图)。如何在排除 td class="quintile detailColumn"?

的同时抓取所有其他 td

我会指定要在 findAll 中使用的所有 classes 并执行 'quintile' not in 但第二列 (2015) 没有 td class。任何帮助将不胜感激,我很乐意澄清我错过的任何事情。谢谢!

使用“.get”获取class如果缺少默认值。然后只需检查该值是否不等于您要排除的值。

像这样(注意 .get('class') returns 中的单词列表 class 而不是字符串):

cols = [ele.text.strip() for ele in cols if ele.get('class',"my default value") != ['quintile', 'detailColumn']]