首页 > 解决方案 > 用漂亮的汤刮网页 4. 删除基于类的 tr 元素。Python

问题描述

我正在从这个页面抓取:' https://kenpom.com/index.php?y=2018 '

我有以下代码:

import requests
from bs4 import BeautifulSoup

url ='https://kenpom.com/index.php?y=2018'
r = requests.get(url).text
soup = BeautifulSoup(r, 'lxml')

table = soup.find('table',{'id':'ratings-table'}).tbody
teams = table.findAll('tr')4

该变量teams包含 367 个tr元素。它们中的大多数没有类,但其中一些具有“thead1”类,有些具有“thead2”类。如何删除具有“thead1”或“thead2”作为类的所有tr元素?teams

标签: pythonhtmlweb-scrapingbeautifulsouptr

解决方案


尝试这个:

[x for x in teams if 'class' not in x.attrs or ('thead1' not in x.attrs['class'] and 'thead2' not in x.attrs['class'])]


推荐阅读