如何使用Python(lxml,html,requests,xpath)从一页获取不同的表?

时间:2019-01-01 14:53:40

标签: python html python-requests lxml

我正在尝试从https://www.premierleague.com/tables获取英超联赛表的数据。我可以通过下面的代码获取数据,但不幸的是,它仅适用于最新的季节选项( 2018/2019 )。该页面还提供其他季节的表格( 2017/2018,...)如何抓取其他表格?

from lxml import html
import requests

page = requests.get('https://www.premierleague.com/tables')

tree = html.fromstring( page.content )

team_rows = tree.xpath('//table//tbody//tr[@data-filtered-table-row-name]')[0:20]
team_names = [i.attrib['data-filtered-table-row-name'] for i in team_rows] 

teams = {}

for i in range(20):
    element = team_rows[i]
    teams[team_names[i]] = element.getchildren()

for i in team_names:
    values = [j.text_content() for j in teams[i]]
    row = "{} "*9
    print( row.format(i, *values[3:12] ) )

1 个答案:

答案 0 :(得分:1)

  

但不幸的是,它仅适用于最新的季节选项(2018/2019)

网站使用JavaScript加载旧表(1992-2017),因此当您使用Python进行访问时,您将获得最新表。如果您希望按年份/会话抓取表格过滤器,我会为您提供一个硬代码版本(因为我没有找到年份编号的规则)。但您想更优雅地完成它,硒或request_html可能适合您。

注意:模仿JavaScript从服务器获取数据,因此响应的内容为json类型。而且只能获得不同年份的英超联赛排行榜。在我的示例中,无法按比赛/比赛周/ home_or_away进行过滤。如果要将这些选项添加到脚本中,则应分析url参数的规则(使用@pguardiario表示的方式或使用诸如fiddler之类的工具)。

import requests
from pprint import pprint

years = {str(1991+i):str(i) for i in range(1,23)}
years.update({
    "2018":"210",
    "2017":"79",
    "2016":"54",
    "2015":"42",
    "2014":"27"
    })

specific = years.get("2017")

param = {
    "altIds":"true",
    "compSeasons":specific,
    "detail":2,
    "FOOTBALL_COMPETITION":1
}

headers = {
    "Origin": "https://www.premierleague.com",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
    "Referer": "https://www.premierleague.com/tables?co=1&se={}&ha=-1".format(specific),
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
    }

page = requests.get('https://footballapi.pulselive.com/football/standings',
                 params=param,
                 headers=headers
                 )
print(page.url)
pprint(page.json())
  

如何从一页获取不同的表

我觉得您的问题标题与您的描述不同。如果是这样,另一个问题是您将所有表合并到一个表中。而且您应该注意// What is meaning of .// in XPath?

注意: 如果要获取英超联赛表的旧数据,请在第一部分中使用我的代码。 ,因为这些数据只能通过这种方式获取。 / p>

from lxml import html
import requests
from pprint import pprint

years = {str(1991+i):str(i) for i in range(1,23)}
years.update({
    "2018":"210",
    "2017":"79",
    "2016":"54",
    "2015":"42",
    "2014":"27"
    })

param = {
    "co":"1",
    "se":years.get("2017"),
    "ha":"-1"
}


page = requests.get('https://www.premierleague.com/tables', params=param)

tree = html.fromstring( page.content )
tables = tree.xpath('//tbody[contains(@class,"tableBodyContainer")]')
each_table_team_rows = [table.xpath('tr[@data-filtered-table-row-name]') for table in tables]
team_names = [[i.attrib['data-filtered-table-row-name'] for i in team_rows] for team_rows in each_table_team_rows]

pprint(team_names)