python - 如何使用 Beautiful Soup(模态容器)抓取 HTML 数据端点

标签 python html web-scraping beautifulsoup

我目前正在尝试从棒球引用中抓取数据,一切都很顺利,除了我在尝试在模式容器/数据端点中抓取数据时遇到了问题。现在,我实际上不了解 HTML,尽管我足够熟悉,可以轻松地进行抓取 - 这就是为什么我不确定是否应该将我尝试输入的内容分类为数据端点或模态容器。希望下面能说清楚:

如果您转到https://www.baseball-reference.com/players/gl.fcgi?id=torregl01&t=b&year=2019 ,我试图从中抓取的示例页面,并查看标记为“PA”的列,您将看到单击该值会加载一个弹出窗口。我试图从该窗口中抓取信息,这就是给我带来问题的原因 - 我根本不知道如何抓取不直接在网页上的信息。

下面是我通过“Inspect”找到的容器的 html: HTML

我还发现每行中的“PA”单元格在其属性中列出了一个数据端点,如下所示: Cell data-endpoint

我不确定如何访问弹出窗口中的信息,如果可能的话,我更愿意使用 Beautiful Soup 来访问。如果有人至少能指出我从这些类型的弹出窗口中抓取信息的正确方向,那将非常有帮助。

非常感谢任何好心帮助我的人 - 我们将非常感激!

最佳答案

我的解决方案仅使用请求和 BeautifulSoup (以及 Pandas 来显示解决方案)。编辑:之前的代码中有粗心的错误。以下内容应采用任何玩家的网址并获取所有弹出窗口。请注意,在多次请求后,程序开始显着变慢。

代码

import requests, re
from bs4 import BeautifulSoup
import pandas as pd

players_list = [
    'https://www.baseball-reference.com/players/gl.fcgi?id=torregl01&t=b&year=2019',
    'https://www.baseball-reference.com/players/gl.fcgi?id=troutmi01&t=b&year=2019',
    'https://www.baseball-reference.com/players/gl.fcgi?id=lindofr01&t=b&year=2019'
]

all_dfs = {}
for player in players_list:
    r = requests.get(player)
    soup = BeautifulSoup(r.text, 'html.parser')
    dates = soup.find_all('td', attrs={'data-stat': 'date_game'})

    player_id = re.search(r'id=(\w+)', player).group(1)
    params = {
        'html': '1',
        'date_out': '1',
        't': 'b'
    }
    popup_url = 'https://www.baseball-reference.com/play-index/be.cgi'
    temp_df_holder = []
    for date in dates:
        if date.get('csk'):
            param_date = re.search(r'\.(\w+)', date['csk']).group(1)
            params['game-id'] = param_date + '-' + player_id
            popup = requests.get(popup_url, params=params)
            print(popup.url)
            df = pd.read_html(popup.text)
            temp_df_holder.append(df)
    all_dfs[player_id] = temp_df_holder
    print(f'Player {player_id} done')

print(all_dfs)

关于python - 如何使用 Beautiful Soup(模态容器)抓取 HTML 数据端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57948765/

相关文章:

python - 如何在 64 位环境中处理 ctypes 中的字符串数组 (char **)?

html - 垂直/水平图像在 DIV 内居中图像

html - 粘性页脚无法与 jquery 动画菜单一起正常工作

python - 确实使用 BeautifulSoup python 抓取前 100 个工作结果

python - tkinter url 请求中没有内容

python - 如果 f-string 像 Julia 中可用的字符串格式?

python - IF 语句并返回 python

html - 使用 VBA 访问 iframe 中的对象

python - 防止 pyttsx3 卡住 GUI

html - 图标不起作用