python - 将网球结果表(包括比赛)刮到每一行

标签 python web-scraping beautifulsoup python-requests

我想从此页面抓取匹配结果:https://www.tennisexplorer.com/player/paire-4a33b/

根据抓取的结果,我想创建包含以下列的表:锦标赛、日期、match_player_1、match_player_2、回合、得分 我创建了一个代码,它可以工作,但我不知道如何向每个匹配行添加竞争

import requests
from bs4 import BeautifulSoup

u = 'https://www.tennisexplorer.com/player/paire-4a33b/'

r = requests.get(u, timeout=120, headers=headers)
# print(r.status_code)
soup = BeautifulSoup(r.content, 'html.parser')

for tr in soup.select('#matches-2020-1-data tr'):
    match_date = tr.select_one('td:nth-of-type(1)').get_text(strip=True)
    match_surface = tr.select_one('td:nth-of-type(2)').get_text(strip=True)
    match = tr.select_one('td:nth-of-type(3)').get_text(strip=True)
#...

我需要创建这样的表:

tournament                      date    match_player_1  match_player_2  round   score
Cincinnati Masters (New York)   22.08.  Coric B.        Paire B.        1R      6-0, 1-0
Ultimate Tennis Showdown 2      01.08.  Moutet C.       Paire B.        NaN     15-0, 15-0, 15-0, 15-0

如何将锦标赛与每场比赛联系起来

最佳答案

要获取所需的 DataFrame,您可以这样做:

import requests
import pandas as pd
from bs4 import BeautifulSoup


url = 'https://www.tennisexplorer.com/player/paire-4a33b/'
soup = BeautifulSoup( requests.get(url).content, 'html.parser' )

all_data = []
for row in soup.select('#matches-2020-1-data tr:not(:has(th))'):
    tds = [td.get_text(strip=True, separator=' ') for td in row.select('td')]
    all_data.append({
        'tournament': row.find_previous('tr', class_='head flags').find('td').get_text(strip=True),
        'date': tds[0],
        'match_player_1': tds[2].split('-')[0].strip(),
        'match_player_2': tds[2].split('-')[-1].strip(),
        'round': tds[3],
        'score': tds[4]
        })

df = pd.DataFrame(all_data)
df.to_csv('data.csv')

保存data.csv(来自 LibreOffice 的屏幕截图):

enter image description here

关于python - 将网球结果表(包括比赛)刮到每一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63548631/

相关文章:

python - 按行将列名从 DataFrame 提取到 Series 中

javascript - 触发 Javascript 函数的 VBA 代码

python - Selenium 蟒 : How to stop page loading when the head/title gets loaded?

python - 如果我使用 lxml 而不是 BeautifulSoup,我会更好地控制我的蜘蛛吗?

python - 在 Python 中使用 BeautifulSoup 解析 <TR> </TR> 标签并打印元素

python - 管道 python 日志记录标准输出流输出到 grep

python - 在列表中的列表中查找项目

python - pandas argsort 的有趣结果

javascript - 从特定远程站点 PHP 抓取信息

python - 如何使用 beautifulsoup 提取段落标签中的完整文本