用 Python 解析直播网站中的台词
我正在尝试从网站上读取不断变化的信息。
例如,假设我想读取在线广播网站上正在播放的艺术家姓名。 我可以获取当前艺术家的姓名,但是当歌曲更改时,HTML 会自行更新,并且我已经通过以下方式打开了文件:
f = urllib.urlopen("SITE")
所以我看不到新歌曲的更新后的艺术家姓名歌曲。
我是否可以在 while(1) 循环中继续关闭和打开 URL 以获取更新的 HTML 代码,或者是否有更好的方法来执行此操作?谢谢!
I'm trying to read in info that is constantly changing from a website.
For example, say I wanted to read in the artist name that is playing on an online radio site.
I can grab the current artist's name but when the song changes, the HTML updates itself and I've already opened the file via:
f = urllib.urlopen("SITE")
So I can't see the updated artist name for the new song.
Can I keep closing and opening the URL in a while(1) loop to get the updated HTML code or is there a better way to do this? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须定期重新下载该网站。不要经常这样做,因为这对服务器来说太难了。
这是因为 HTTP 本质上不是流协议。连接到服务器后,它会期望您向其发出 HTTP 请求,然后它会向您发出包含该页面的 HTTP 响应。如果您的初始请求是保持活动的(从 HTTP/1.1 开始默认),您可以再次抛出相同的请求并使页面保持最新。
我会推荐什么?根据你的需求,每隔n秒获取一次页面,获取你需要的数据。如果该网站提供 API,您就可以利用它。另外,如果这是您自己的站点,您也许能够通过 HTTP 实现 Comet 风格的 Ajax 并获得真正的流。
另请注意,如果这是其他人的页面,则该网站可能通过 Javascript 使用 Ajax 来使其保持最新;这意味着还有其他请求导致更新,您可能需要仔细分析网站以找出需要发出哪些请求才能获取数据。
You'll have to periodically re-download the website. Don't do it constantly because that will be too hard on the server.
This is because HTTP, by nature, is not a streaming protocol. Once you connect to the server, it expects you to throw an HTTP request at it, then it will throw an HTTP response back at you containing the page. If your initial request is keep-alive (default as of HTTP/1.1,) you can throw the same request again and get the page up to date.
What I'd recommend? Depending on your needs, get the page every n seconds, get the data you need. If the site provides an API, you can possibly capitalize on that. Also, if it's your own site, you might be able to implement comet-style Ajax over HTTP and get a true stream.
Also note if it's someone else's page, it's possible the site uses Ajax via Javascript to make it up to date; this means there's other requests causing the update and you may need to dissect the website to figure out what requests you need to make to get the data.
如果您使用 urllib2,您可以在发出请求时读取标头。如果服务器在标头中发回“304 Not Modified”,则内容没有更改。
If you use urllib2 you can read the headers when you make the request. If the server sends back a "304 Not Modified" in the headers then the content hasn't changed.
是的,这是正确的做法。要获取网络中的更改,您必须每次都发送新的查询。实时 AJAX 站点的内部执行完全相同的操作。
有些网站提供额外的 API,包括长轮询。在网站上查找文档或询问他们的开发人员是否有一些文档。
Yes, this is correct approach. To get changes in web, you have to send new query each time. Live AJAX sites do exactly same internally.
Some sites provide additional API, including long polling. Look for documentation on the site or ask their developers whether there is some.