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

标签 python html web-scraping beautifulsoup get

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

这是网站网址: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/

相关文章:

html - 图像高度与宽度相同

javascript - 将 Angular 物体绑定(bind)到 Polymer 1.0

javascript - 当来自彭博网址的请求时我无法获取正文

python-3.x - 使用 python 抓取网站搜索栏

python - 复制时为 "pygame.error: No available video device"

python - 将列表中相似的字符串分组在一起

javascript - 如何检测文档是否回到焦点?

python - 列表、文件和读取行

python - os.rename 不起作用

模拟点击链接的C#代码