【问题标题】:Get fully generated DOM elements inside iframe using selenium and phantomJS with python使用 selenium 和 phantomJS 和 python 在 iframe 中获取完全生成的 DOM 元素
【发布时间】:2020-12-18 11:48:42
【问题描述】:

好的,我卡住了。我使用 selenium 和 PhantomJS 制作了一个小的网络抓取 python 脚本。我正在处理的页面在我的网络驱动程序未运行的 iframe 文档中包含我想要的数据。

<main Page Heads etc>

   <blah>

   <iframe 1 src="src1" ... etc etc>
    #document
      <tag>
      <tag>
      <iframe2 src="src2"><iframe2>
   <iframe1>

   <blah>

<end of webpage DOM>

我想得到iframe2src。我试图通过我的网络驱动程序运行src1 URL,但我得到的只是原始页面 html,而不是加载的网页元素,iframe2 必须由iframe1 中的某些脚本创建,但我无法获得我的webdriver 来运行脚本。

有什么想法吗?

这就是我在网页上运行 javascript 以获取已编译的页面 DOM:

from selenium import webdriver 

self.driver = webdriver.PhantomJS()
self.driver.get(url)
page = self.driver.page_source
soup = BeautifulSoup(page,'html.parser')

【问题讨论】:

    标签: python selenium iframe phantomjs


    【解决方案1】:

    您无法获得完整的 page_source。在iframe的情况下,你应该使用下面的命令:switch_to.frame(iframe_element),这样你就可以得到一个里面的元素

    from selenium import webdriver
    from selenium.webdriver.support.wait import WebDriverWait
    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.common.by import By
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.support import expected_conditions as EC
    
    self.driver = webdriver.PhantomJS()
    self.driver.get(url)
    
    
    
    WebDriverWait(self._driver, 50).until(
                EC.presence_of_all_elements_located
                ((By.XPATH,
                  '//iframe[@id="iframegame"]'))
            )
    
    iframe_element = self.driver.find_element_by_xpath('//iframe[@id="iframegame"]')
    
    self.driver.switch_to.frame(iframe_element)
    
    tag = self.driver.find_element_by_xpath('//tag')
    

    再次返回,您可以使用以下命令获取 iframe 的外部元素;

    self.driver.switch_to.default_content()
    

    【讨论】:

    • 我试过但我得到了:File "NBA/getLinks_nbastream_bilasport.py", line 112, in getIframeLink self.driver.switch_to.frame(iframe1) TypeError: Object of type 'Tag' is not JSON serializable
    • 你能分享你的结果吗?
    • 能否分享完整的html代码或网站链接?
    • 这就是 iframe1 的样子:&lt;iframe allowfullscreen="" frameborder="0" height="100%" id="iframegame" scrolling="no" src="http://bilasport.net/iframes/d/toronto-raptors-vs-boston-celtics-25247.html" width="100%"&gt;&lt;/iframe&gt; 我不能把整件事都写出来,因为这个评论框不允许我
    • 当我在 chrome 中“检查”页面时,iframe1 充满了其他元素,包括 iframe2。但我仍然只能用我的脚本获取源 html
    猜你喜欢
    • 2016-12-12
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多