【问题标题】:Python WebDriver how to print whole page source (html)Python WebDriver如何打印整个页面源(html)
【发布时间】:2014-12-10 22:17:54
【问题描述】:

我正在使用带有 Selenium WebDriver 的 Python 2.7。 我的问题是如何使用print 方法打印整个页面源。 有 webdriver 方法 page_source 但它返回 WebDriver 我不知道如何将其转换为字符串或只是在终端打印它

【问题讨论】:

    标签: python selenium-webdriver webdriver


    【解决方案1】:

    webdriver 实例上的.page_source 是您所需要的:

    >>> from selenium import webdriver
    >>> driver = webdriver.Firefox()
    >>> driver.get('http://google.com')
    >>> print(driver.page_source)
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml" lang="en" itemtype="http://schema.org/WebPage" itemscope=""><head><meta name="descri
    ...
    :before,.vscl.vslru div.vspib{top:-4px}</style></body></html>
    

    【讨论】:

    • 谢谢,这正是我需要的!那是我的错,因为我做得不好print driver.page_source(driver.page_source 不在括号中)
    • page_source 似乎只是可见的,而不是整个 html 源代码。
    【解决方案2】:

    您也可以在不使用浏览器的情况下获取 HTML 页面源代码。 requests 模块允许您这样做。

     import requests
    
     res = requests.get('https://google.com')
     res.raise_for_status()  # this line trows an exception if an error on the 
                             # connection to the page occurs. 
     print(res.text)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 2012-04-07
      相关资源
      最近更新 更多