【问题标题】:Python bad request in GET but wget and curl workGET中的Python错误请求但wget和curl工作
【发布时间】:2016-01-31 15:24:04
【问题描述】:

我正在尝试使用请求在 python 中执行获取请求,但我收到 400 bad request 错误。但是,当我在同一个 url 上执行 wget 或 curl 时,它可以工作。这是我的代码:

daily_scoreboard_url = 'http://stats.nba.com/stats/scoreboardV2?DayOffset=0&LeagueID=00&gameDate=01/12/2016'
scoreboard_response = requests.get(daily_scoreboard_url)
scoreboard_response.raise_for_status()

但是,当我尝试类似的事情时

curl 'http://stats.nba.com/stats/scoreboardV2?DayOffset=0&LeagueID=00&gameDate=01/12/2016'
wget 'http://stats.nba.com/stats/scoreboardV2?DayOffset=0&LeagueID=00&gameDate=01/12/2016'

它有效。我还尝试使用 stats.nba.com 的其他内容的获取请求,并且成功了。

teamslist_url = 'http://stats.nba.com/stats/leaguedashteamstats?Conference=&DateFrom=&DateTo=&Division=&GameScope=&GameSegment=&LastNGames=0&LeagueID=00&Location=&MeasureType=Base&Month=0&OpponentTeamID=0&Outcome=&PORound=0&PaceAdjust=N&PerMode=PerGame&Period=0&PlayerExperience=&PlayerPosition=&PlusMinus=N&Rank=N&Season=2015-16&SeasonSegment=&SeasonType=Regular+Season&ShotClockRange=&StarterBench=&TeamID=0&VsConference=&VsDivision='
teamslist_response = requests.get(teamslist_url)
teamslist_response.raise_for_status()

【问题讨论】:

    标签: python curl python-requests


    【解决方案1】:

    你需要give requests a user-agent:

    >>> headers = {'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36'}
    >>> scoreboard_response = requests.get(daily_scoreboard_url, headers=headers)
    >>> scoreboard_response
    <Response [200]>
    

    那是网站的错,不是reuqests 的。有些网站需要用户代理来检查您是人类还是机器人/脚本。

    但是,我们可以手动设置用户代理。在示例中,这是我的 Chrome 的用户代理。

    【讨论】:

    • 谢谢,这成功了!但出于好奇,为什么我不需要另一个 url 的用户代理才能工作?
    • @birna:正如我所说,有些网站需要用户代理来检查你是人类还是机器人/脚本。 似乎这个网站不允许没有用户代理的请求。它是由网站所有者设置的。
    猜你喜欢
    • 2019-07-15
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 2014-07-05
    • 1970-01-01
    相关资源
    最近更新 更多