gpt4 book ai didi

python - Beautifulsoup 带有下拉菜单的网页抓取网站

转载 作者:行者123 更新时间:2023-12-04 17:38:10 27 4
gpt4 key购买 nike

我正在尝试抓取一个具有下拉菜单的站点,用户可以在其中选择要显示的数据的年份。但是,我似乎被困在我的实现中。

这是网站网址:https://www.pgatour.com/tournaments/masters-tournament/past-results.html

这是一个个人项目,用于收集每年每个主要锦标赛的高尔夫数据。我知道如何在选择年份后提取所需的统计数据。

这是下拉菜单的网站 html 示例

<select name="year" id="pastResultsYearSelector" class="hasCustomSelect"
style="-webkit-appearance: menulist-button; width: 180px; position: absolute;
opacity: 0; height: 42px; font-size: 18px;">
<option value="2019" selected="selected">2019</option>
<option value="2018">2018</option>
<option value="2017">2017</option>
<option value="2016">2016</option>

到目前为止,这是我尝试过的:

headers = {
'user-agent':
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36'
}

data = {
'name':'2019', 'id':'pastResultYearSelector', 'class':'hasCustomSelect',
'style':'-webkit-appearance: menulist-button; width: 180px; position: absolute; opacity: 0; height: 42px; font-size: 18px;'
}

url = "https://www.pgatour.com/tournaments/masters-tournament/past-results.html"

r = requests.post(url, data=data, headers=headers, timeout=20)

soup = BeautifulSoup(r.text, 'html.parser')

但是我的请求似乎是无效的,因为我收到一个回复​​说找不到请求的页面。

最佳答案

正如评论中提到的,您可以使用以下 url 结构,页面按年份更新内容

import requests
from bs4 import BeautifulSoup as bs

r = requests.get('https://www.pgatour.com/content/pgatour/tournaments/masters-tournament/past-results/jcr:content/mainParsys/pastresults.selectedYear.{}.html'.format(2017))

soup = bs(r.content, 'lxml')

你会想要做一些数据框的整理,但你可以使用 pandas 来抓取表的句柄

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

r = requests.get('https://www.pgatour.com/content/pgatour/tournaments/masters-tournament/past-results/jcr:content/mainParsys/pastresults.selectedYear.{}.html'.format(2017))
soup = bs(r.content, 'lxml')
table = pd.read_html(str(soup.select_one('table')))[0]

关于python - Beautifulsoup 带有下拉菜单的网页抓取网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55719197/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com