python實現網頁截圖


這是windows下面的截圖方法,實現方法都用了selenium

依賴庫如下所示:

pip install selenium==2.48.0

方法一:

代碼如下所示:

import time
from selenium import webdriver


def jieTu(reqUrl):
    br = webdriver.PhantomJS(executable_path=r'D:\phantomjs-2.1.1-windows\bin\phantomjs')
    br.maximize_window()
    br.get(reqUrl)
    time.sleep(5)
    picName = reqUrl[reqUrl.rfind('/'):][1:].replace(".html", "")
    br.save_screenshot("./savehtml/picture/{}.png".format(picName))
    return str(picName)+'.png'


if __name__ == '__main__':
    url = "https://www.baidu.com"
    # pic_name = url[url.rfind('/'):][1:].replace(".html", ".png")
    # print(pic_name)
    jieTu(url)

注意:在這里,如果沒有phantomjs.exe文件將會報錯

phantomjs下載地址(根據自己電腦的系統下):

https://phantomjs.org/download.html

方法二:

代碼如下所示:

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

URL = 'https://www.baidu.com/'
# 用selenium打開網頁
# (首先要下載 Chrome webdriver, 或 Chrome webdriver)
ch_options = Options()
ch_options.add_argument("--disable-blink-features=AutomationControlled")
# 在啟動瀏覽器時加入配置
driver = webdriver.Chrome(executable_path=r"D:\chromedriver.exe", chrome_options=ch_options)
driver.get(URL)
print(driver.page_source)
time.sleep(5)
driver.save_screenshot("./timeline.png")

注意:在這里需要下載的是chromedriver(版本需要與自己的google瀏覽器版本對應,系統與電腦的系統相匹配)

驅動下載地址:

https://npm.taobao.org/mirrors/chromedriver/

 方法三:

此方法能夠實現截圖,但是達不到預想的效果,也有可能是自己寫的不完善,在這里粘貼代碼,是為了能夠記錄實現這種功能,自己所做的測試案例

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
chrome_options = Options()
driver = webdriver.Chrome(executable_path="D:\chromedriver.exe", chrome_options=ch_options)  # => 注意這里的參數
driver.maximize_window()  # 設置phantomjs瀏覽器全屏顯示
start_url = "https://www.baidu.com/"
driver.get(start_url)
time.sleep(1)
# 獲取區域塊
# imgelement = driver.find_element_by_xpath('//ul[@class="horizontal-list"][1]')
imgelement = driver.find_element_by_xpath('//html[@class="js"][1]')
print("********************************************")
print(imgelement)

# 圖片坐標
locations = imgelement.location
print(locations)
# 圖片大小
sizes = imgelement.size
print(sizes)
# 構造指數的位置
# rangle = (
# int(locations['x']), int(locations['y']), int(locations['x'] + sizes['width']), int(locations['y'] + sizes['height']))
rangle = (
    int(500 + locations['x']), 3500 + int(locations['y']), 500 + int(locations['x'] + sizes['width']),
    3500 + int(locations['y'] + sizes['height']))
print(rangle)
save_path = "D:\\programming\\Replay\\screenshot\\test2.png"
driver.save_screenshot(save_path)
driver.close()

 注意:此方法的實現,也利用了chormedirver,下載地址如下:

https://npm.taobao.org/mirrors/chromedriver/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM