分析网页信息时遇到嵌套html结构该怎么办?


关键词:爬虫、iframe/frame、网页结构、html、selenium、webdriver

遇到的问题

在这里插入图片描述
遇到的网页就像图中的那样,在使用webdriver.page_source()方法获取网页的html内容时,默认获取的是框架1中的内容,嵌套的内容是获取不到的。概念上讲,二者相互独立,是两个html文档树。

接下来先了解一下iframe/frame标签的作用:

iframe 标签

定义和用法

iframe 元素会创建包含另外一个文档的内联框架(即行内框架)。

更详细的内容可以浏览这个链接:http://www.w3school.com.cn/tags/tag_iframe.asp

现在已经可以了解到,嵌套行内框架是通过<iframe> ...</iframe>标签来实现的,也就是说我们只要找到一种能切换到行内框架的方法就行了,这样我们就能切换到这个框架中,然后再使用webdriver.page_source()方法,就能获取到这个嵌套框架的html文档树。

webdriver

刚好,强大的selenium webdriver已经为我们准备好这个方法了,那就是webdriver.switch_to.frame()方法(switch_to 切换;frame 框架)

driver=webdriver.Chrome()
driver.get(LOGIN)
html=driver.page_source
print(html)
print('-----------------------这是分割线-----------------------------')
driver.switch_to.frame(1)       #切换html框架
print(driver.page_source)

效果

在这里插入图片描述
在这里插入图片描述

分析、更多的用法

webdriver.switch_to.frame()方法接受的参数有标签(id、name、index)以及selenium的WebElement对象。

这是定位到的源码

    def switch_to(self):
        """
        :Returns:
            - SwitchTo: an object containing all options to switch focus into

        :Usage:
            element = driver.switch_to.active_element
            alert = driver.switch_to.alert
            driver.switch_to.default_content()
            driver.switch_to.frame('frame_name')		#根据标签名进行切换
            driver.switch_to.frame(1)    #根据框架索引进行切换[0,1,2,...,n-1]
            driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0])    #如果有多个iframe标签,[0]是只第一个
            driver.switch_to.parent_frame()		#切换到父框架
            driver.switch_to.window('main')		#切换到主窗口
        """
        return self._switch_to
    def frame(self, frame_reference):
        """
        Switches focus to the specified frame, by index, name, or webelement.

        :Args:
         - frame_reference: The name of the window to switch to, an integer representing the index,
                            or a webelement that is an (i)frame to switch to.

        :Usage:
            driver.switch_to.frame('frame_name')
            driver.switch_to.frame(1)
            driver.switch_to.frame(driver.find_elements_by_tag_name("iframe")[0])
        """
        if isinstance(frame_reference, basestring) and self._driver.w3c:
            try:
                frame_reference = self._driver.find_element(By.ID, frame_reference)
            except NoSuchElementException:
                try:
                    frame_reference = self._driver.find_element(By.NAME, frame_reference)
                except NoSuchElementException:
                    raise NoSuchFrameException(frame_reference)

推荐阅读

Python+webdriver切换iframe/frame
https://www.cnblogs.com/yaoze2018/p/10403691.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值