Python WebDriver如何打印整个页面源代码(HTML)

23
我正在使用Python 2.7和Selenium WebDriver。 我的问题是如何使用print方法打印整个页面源代码。 有一个webdriver方法page_source,但它返回WebDriver对象,我不知道如何将其转换为字符串或在终端中打印。
2个回答

44

.page_sourcewebdriver 实例上是你所需要的:

>>> 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>

2
谢谢你,这正是我所需要的! 那是我的错,因为我用了错误的方式print driver.page_source(driver.page_source没有括号)。 - wmarchewka
page_source 似乎只显示可见部分,而非整个 HTML 源代码。 - Zach

-3

你也可以在不使用浏览器的情况下获取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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接