不为别的,只为做一个连自己都羡慕的人

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/

 

posted @ 2021-11-03 15:22  升级打怪  阅读(1662)  评论(0编辑  收藏  举报