python beautifulsoup iframe文档html提取

时间:2014-04-12 09:37:10

标签: python html iframe beautifulsoup

我正在尝试学习一些美味的汤,并从一些iFrame中获取一些HTML数据 - 但到目前为止我还没有取得很大成功。

因此,解析iFrame本身似乎不是BS4的问题,但我似乎没有从中获取嵌入内容 - 无论我做什么。

例如,考虑下面的iFrame(这是我在chrome开发人员工具上看到的):

<iframe frameborder="0" marginwidth="0" marginheight="0" scrolling="NO"
src="http://www.engineeringmaterials.com/boron/728x90.html "width="728" height="90">
#document <html>....</html></iframe>

其中,<html>...</html>是我有兴趣提取的内容。

但是,当我使用以下BS4代码时:

iFrames=[] # qucik bs4 example
for iframe in soup("iframe"):
    iFrames.append(soup.iframe.extract())

我明白了:

<iframe frameborder="0" marginwidth="0" marginheight="0" scrolling="NO" src="http://www.engineeringmaterials.com/boron/728x90.html" width="728" height="90">

换句话说,我在其中没有文档<html>...</html>的情况下获得了iFrame。

我尝试了以下几点:

iFrames=[] # qucik bs4 example
iframexx = soup.find_all('iframe')
for iframe in iframexx:
    print iframe.find_all('html')

..但这似乎不起作用..

所以,我想我的问题是,如何从iFrame元素中可靠地提取这些文档对象<html>...</html>

1 个答案:

答案 0 :(得分:13)

浏览器在单独的请求中加载iframe内容 。你必须这样做:

for iframe in iframexx:
    response = urllib2.urlopen(iframe.attrs['src'])
    iframe_soup = BeautifulSoup(response)

请记住:BeautifulSoup不是浏览器;它也不会为您提取图像,CSS和JavaScript资源。