python - 模拟浏览器访问加载所有html元素

标签 python beautifulsoup urllib mechanize-python

我正在尝试加载 YouTube 页面并获取 <embed>元素如下。但是,找不到嵌入元素( soup.find('embed') 返回 None )。

import urllib
import urllib2
from bs4 import BeautifulSoup
import mechanize

YT_URL = 'http://www.youtube.com/watch'
vidId = 'OuSdU8tbcHY'

br = mechanize.Browser()
# Browser options
br.set_handle_equiv(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
br.open('%s?v=%s' % (YT_URL, vidId))
soup = BeautifulSoup(br.response().read())
print soup.find('embed')

但是,当我将汤写入 html 文件并将其加载到浏览器中时,它会加载 <embed>元素。据推测,这与浏览器与机械化不同以及某种document.onload()有关。魔法?

如何模拟浏览器加载页面,以便我可以看到<embed>元素?

最佳答案

页面使用js动态加载内容。机械化根本无法应对。您在这里有两个选择:

  • 尝试在脚本中手动模拟这些js调用
  • 切换到浏览器内工具,例如 selenium

这是使用selenium的相同示例:

import selenium.webdriver as webdriver

url = "http://www.youtube.com/watch?v=OuSdU8tbcHY"

driver = webdriver.Firefox()
driver.get(url)

embed = driver.find_elements_by_tag_name('embed')[0]

print embed

希望有帮助。

关于python - 模拟浏览器访问加载所有html元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18383574/

相关文章:

python - 美汤刮 table 4

html - 将 io.BytesIO 转换为 io.StringIO 来解析 HTML 页面

python-3.x - AttributeError: 'module' 对象没有属性 'urlretrieve'

python - OpenCV中的图像阈值

python - 如何使用 SQLAlchemy 只创建一张表?

Python/pandas - 将条件小时转换为分钟

python - 使用Python + BeautifulSoup串联提取标签,创建列表列表

python - 使用 Beautifulsoup 和选择器检索内容

python - 一分为二并列出用户定义的对象 (python 3)