Python - 使用 urllib2 检索动态内容

发布于 2024-12-20 15:29:11 字数 273 浏览 2 评论 0原文

我正在尝试将 YouTube 链接嵌入网页中。当我使用 urllib2 检索页面时,我在响应中看不到该链接。我认为嵌入的视频是通过页面上的脚本检索的,当我使用浏览器时会加载该脚本。如何使用 python 的 urllib2 获得相同的结果?

示例网页为 http://busymovies.appspot.com/News.html?id=2965032

I am trying to get youtube links embedded in a webpage. When I retrieve the page using urllib2 I don't see the link in the response. I think the embedded video is retrieved by a script on the page which gets loaded when I use a browser. How do I get the same using python's urllib2 ?

A sample webpage is http://busymovies.appspot.com/News.html?id=2965032

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酷到爆炸 2024-12-27 15:29:11

要提取动态生成的(使用 JavaScript)内容,您可以使用 selenium

#!/usr/bin/env python
from contextlib import closing
from selenium.webdriver import Firefox # pip install selenium

url = "http://busymovies.appspot.com/News.html?id=2965032"

# use firefox to get page with javascript generated content
with closing(Firefox()) as browser:
    browser.get(url)
    link = browser.find_element_by_link_text("Direct Link")
    print link.get_attribute("href")

http://www.youtube.com/v/nLJYkat4HpE&hl=en_US&feature=player_embedded&version=3

To extract dynamically generated (with javascript) content you could use selenium:

#!/usr/bin/env python
from contextlib import closing
from selenium.webdriver import Firefox # pip install selenium

url = "http://busymovies.appspot.com/News.html?id=2965032"

# use firefox to get page with javascript generated content
with closing(Firefox()) as browser:
    browser.get(url)
    link = browser.find_element_by_link_text("Direct Link")
    print link.get_attribute("href")

Output

http://www.youtube.com/v/nLJYkat4HpE&hl=en_US&feature=player_embedded&version=3
萝莉病 2024-12-27 15:29:11

视频正下方有一个名为“直接链接”的链接。现在,如果您打开源代码,您将看到它的结构。

在此处输入图像描述

您所需要做的就是解析 HTML 和使用id=directlink到达此节点。您可以使用 BeautifulSoup 来实现这一点。你都准备好了...

Right below the video there is a link called "Direct Link". Now if you open the source you'll see its structure.

enter image description here

All you need to do is parse the HTML & get to this node with id=directlink. You could use BeautifulSoup for that. You are all set...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文