简体   繁体   English

如果没有先在浏览器中打开它,就无法在 Python 中打开它

[英]Can't open an URL in Python without opened it in browser first

I want to make a bot that tweet NBA Scores every day.我想制作一个每天发布 NBA 得分的机器人。 So I need to get the NBA Scores from the stats.nba website every day.所以我需要每天从 stats.nba 网站上获取 NBA 得分。 The problem is if I don't click on the JSON link and access it with my browser before trying to open it in my code it doesn't work.问题是,如果我在尝试在我的代码中打开它之前不单击 JSON 链接并使用浏览器访问它,则它不起作用。 There is a new link every day for the matchs of the night.每天都有一个晚上比赛的新链接。

Does anyone know how to solve that ?有谁知道如何解决这个问题? Thank you谢谢

It would be interesting to see your code and figure out why it needs to be opened in the browser first, but if that really is the case:查看您的代码并弄清楚为什么需要先在浏览器中打开它会很有趣,但如果确实如此:

Just open it with webbrowser first:只需先用网络浏览器打开它:

import webbrowser
webbrowser.open_new_tab(url)
# rest of your logic below.

This will open the url in your systems default browser.这将在您的系统默认浏览器中打开该 url。

You could also check if you're missing some flags such as allowing for redirects or if you need an user-agent (so it looks like you're visiting from a browser)您还可以检查是否缺少一些标志,例如允许重定向或是否需要用户代理(因此看起来您是从浏览器访问的)

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
response = requests.get(url, headers=headers, allow_redirects = True)
response.raise_for_status()
content = response.text

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM