簡體   English   中英

Python WebDriver如何打印整頁源碼(html)

[英]Python WebDriver how to print whole page source (html)

我正在使用Python 2.7和Selenium WebDriver。 我的問題是如何用print方法打印整頁源。 有webdriver方法page_source但它返回WebDriver,我不知道如何將其轉換為String或只是在終端打印

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>

您還可以在不使用瀏覽器的情況下獲取HTML頁面源。 請求模塊允許您這樣做。

 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM