我正在使用Python 2.7和Selenium WebDriver。
我的问题是如何使用
print
方法打印整个页面源代码。
有一个webdriver方法page_source
,但它返回WebDriver对象,我不知道如何将其转换为字符串或在终端中打印。print
方法打印整个页面源代码。
有一个webdriver方法page_source
,但它返回WebDriver对象,我不知道如何将其转换为字符串或在终端中打印。.page_source
在 webdriver
实例上是你所需要的:
>>> 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>
你也可以在不使用浏览器的情况下获取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)
print driver.page_source
(driver.page_source没有括号)。 - wmarchewka