Python - 使用urllib2获取动态内容
我想把YouTube链接嵌入到一个网页里。当我用urllib2获取这个网页时,发现响应中没有这个链接。我觉得这个嵌入的视频是通过网页上的一个脚本获取的,而这个脚本在我用浏览器打开网页时才会加载。请问我怎么才能用Python的urllib2做到这一点呢?
2 个回答
0
在视频下面,有一个叫“直接链接”的链接。如果你查看网页的源代码,就能看到它的结构。
你需要做的就是解析这个HTML,找到一个id=directlink
的节点。你可以使用BeautifulSoup来完成这个任务。这样就可以了……
3
如果你想提取那些用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