Chrome截圖保存在本地并通過郵件發(fā)送多張圖片

1. 準(zhǔn)備工作

????Chrome下載和ChromeDriver下載(注意:瀏覽器的版本和驅(qū)動的版本一定要匹配

????下載鏈接可參考:https://blog.csdn.net/seedinspring/article/details/89850331

????將ChromeDriver解壓到 /python3/lib/python3.6/site-packages/selenium/webdriver/chrome/ 這個文件夾下

2. 截圖代碼

from selenium import webdriver

from selenium.webdriver.chrome.options import Options

from PIL import Image

# 截圖配置信息

chrome_options = Options()

chrome_options.add_argument('--no-sandbox')

chrome_options.add_argument('--disable-dev-shm-usage')

chrome_options.add_argument('--headless')

# 啟動Chrome

driver = webdriver.Chrome(executable_path="ChromeDriver的位置", chrome_options=chrome_options)

# Chrome界面最大化

driver.maximize_window()

# 設(shè)置圖片分辨率

driver.set_window_size(1366, 768)

# 訪問圖片的url

driver.get('圖片所在的url')

sleep(3)

# 截取整個網(wǎng)頁上某一張圖片

driver.save_screenshot('全屏圖片保存地址')

img = driver.find_element_by_css_selector("[class='f12查看class名,寫到這里']")? # 根據(jù)class來選取其中某一張圖片

# 這一張圖片的上、下、左、右

left = img.location['x']

top = img.location['y']

right = img.location['x'] + img.size['width']

bottom = img.location['y'] + img.size['height']

# 定位并保存

photo = Image.open('全屏圖片保存地址')

photo = photo.crop((left, top, right, bottom))

photo.save('這一張圖片的保存的地址')

# 退出Chrome

driver.quit()


3. 發(fā)送多張圖片代碼

def send_email_common(subject,content,to_list,cc_list,bbs=False,img=None):

????pass

4. jinja2模板代碼

Jinja2是基于python模板引擎,Flask使用jinja2作為框架的模板系統(tǒng),使用django等其他Python web框架也可以方便的集成jinja2模板系統(tǒng)。jinja2更多模板書寫參考:https://www.w3cschool.cn/yshfid/


# loop.index是循環(huán)的次數(shù),從1開始

# loop.index|string將數(shù)字轉(zhuǎn)換為字符串

# with中的tmp是局部變量,只能在with中使用

# cid是發(fā)郵件時圖片src的寫法

{% if exception_list %}

? ? {% for row in exception_list %}

? ? ? ? <h4>{{ row.instance__instance_name }}風(fēng)險(xiǎn)詳情:<a href={{ row.url }}>圖片鏈接</a></h4><br>

? ? ? ? {% with tmp="image" + loop.index|string %}

? ? ? ? ? ? <img src="cid:{{ tmp }}" alt="imageid" width="1200"><br>

? ? ? ? {% endwith %}

? ? {% endfor %}

{% endif %}

5. 補(bǔ)充一個小技能(圖片拼接)

from PIL import Image

if id_list:

? ? im_list = []

? ? for id in id_list:

? ? ? ? im_list.append(Image.open('./Screenshots/%s.png' % id))

? ? # print(im_list)

? ? width, height = im_list[0].size

? ? result = Image.new(im_list[0].mode, (width, height * len(im_list)))

? ? for i, im in enumerate(im_list):

? ? ? ? result.paste(im, box=(0, i * height))

? ? result.save('./Screenshots/%s.png' % datetime.date.today().strftime('%Y%m%d'))

? ? with open('./Screenshots/%s.png' % datetime.date.today().strftime('%Y%m%d'), 'rb') as f:

? ? img = f.read()

? ? print(img)

6. 總結(jié)

????最后實(shí)現(xiàn)的功能是在郵件中一個url對應(yīng)一張圖片

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容