【问题标题】:Beautifulsoup web-scraping website with drop down menuBeautifulsoup 网页抓取网站,带有下拉菜单
【发布时间】:2019-09-07 04:58:33
【问题描述】:

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

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

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

【问题讨论】:

  • 如果页面使用 Ajax,则数据在页面加载后加载。您可以使用浏览器上的开发者工具来仔细检查。
  • 考虑一下 selenium。
  • baseURL: "/content/pgatour/tournaments/masters-tournament/past-results/jcr:content/mainParsys/pastresults.selectedYear。"你见过这个吗?我认为您发布到错误的网址。

标签: python html web-scraping beautifulsoup get


【解决方案1】:

正如在 cmets 中提到的,您可以使用以下 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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多