Skip to main content
 首页 » 编程设计

Python 抓取表

2025年05月04日22zengkefu

我是编程新手,所以我想做的事情很可能完全不是这样做的方法。

我正在尝试从该站点抓取排名表 - http://www.flashscore.com/hockey/finland/liiga/ - 现在,如果我什至可以用团队名称抓取一列就好了,所以我尝试找到类为“participant_name col_participant_name col_name”的 td 标签,但代码返回空括号:

import requests 
from bs4 import BeautifulSoup 
import lxml 
 
def table(url): 
    teams = [] 
    source = requests.get(url).content 
    soup = BeautifulSoup(source, "lxml") 
    for td in soup.find_all("td"): 
        team = td.find_all("participant_name col_participant_name col_name") 
        teams.append(team) 
        print(teams) 
 
table("http://www.flashscore.com/hockey/finland/liiga/") 

我尝试使用 tr 标签检索整行,但也没有成功。

请您参考如下方法:

我认为这里的主要问题是您正在尝试使用 requests 抓取动态生成的内容,请注意 HTML 中根本没有 participant_name col_participant_name col_name 文本页面的来源,这意味着这是由网站使用 JavaScript 生成的。对于那个工作,你应该使用类似 selenium 的东西连同 ChromeDriver或者您发现更好的驱动程序,下面是使用上述两种工具的示例:

from bs4 import BeautifulSoup 
from selenium import webdriver 
 
url = "http://www.flashscore.com/hockey/finland/liiga/" 
 
driver = webdriver.Chrome() 
driver.get(url) 
 
source = driver.page_source 
 
soup = BeautifulSoup(source, "lxml") 
elements = soup.findAll('td', {'class':"participant_name col_participant_name col_name"}) 

我认为您的代码的另一个问题是您尝试访问标签的方式,如果您想匹配特定的 class 或任何其他特定的属性,您可以使用 Python 的字典来实现.findAll 函数的参数。

现在我们可以使用 elements 来查找所有团队的名称,尝试 print(elements[0]) 并注意团队名称在 中a 标签,我们可以使用 .a.text 访问它,所以像这样:

teams = [] 
for item in elements: 
    team = item.a.text 
    print(team) 
    teams.append(team) 
 
print(teams) 

teams 现在应该是所需的输出:

>>> teams 
['Assat', 'Hameenlinna', 'IFK Helsinki', 'Ilves', 'Jyvaskyla', 'KalPa', 'Lukko', 'Pelicans', 'SaiPa', 'Tappara', 'TPS Turku', 'Karpat', 'KooKoo', 'Vaasan Sport', 'Jukurit'] 

团队也可以使用列表理解来创建:

teams = [item.a.text for item in elements]