driver = webdriver.Chrome() driver.get('http://www.baidu.com/') driver.maximize_window() driver.implicitly_wait(10) #保存需要截图的图片,登录页面图片 sleep(3) driver.save_screenshot('截图.png') #找到元素,定义变量 picture = driver.find_element(By.CSS_SELECTOR,'#su') #定义图片的4个点,X轴Y轴,最右边以及最左边 left = picture.location['x'] top = picture.location['y'] right = picture.size['width']+left bottom = picture.size['height']+top print (left,top,right,bottom) #打开图片 ima = Image.open('截图.png') #.crop()对图片进行裁剪 ima = ima.crop((left,top,right,bottom)) ima.save('picture.png') sleep(3)这行代码写成一个类
时间: 2024-01-13 18:05:34 浏览: 221
Chrome无头模式–headless1
可以将上述代码封装成一个名为 `Screenshot` 的类,实现截图功能。以下是示例代码:
```python
from selenium import webdriver
from selenium.webdriver.common.by import By
from time import sleep
from PIL import Image
class Screenshot:
def __init__(self, url):
self.driver = webdriver.Chrome()
self.url = url
def get_screenshot(self, element_css_selector, save_path):
self.driver.get(self.url)
self.driver.maximize_window()
self.driver.implicitly_wait(10)
sleep(3)
self.driver.save_screenshot(save_path)
element = self.driver.find_element(By.CSS_SELECTOR, element_css_selector)
left = element.location['x']
top = element.location['y']
right = element.size['width'] + left
bottom = element.size['height'] + top
ima = Image.open(save_path)
ima = ima.crop((left, top, right, bottom))
ima.save(save_path)
def quit(self):
self.driver.quit()
```
使用方法:
```python
s = Screenshot('http://www.baidu.com/')
s.get_screenshot('#su', 'picture.png')
s.quit()
```
其中,`url` 参数传入需要截图的网址,`element_css_selector` 参数传入需要截图的元素的 CSS 选择器,`save_path` 参数传入截图保存的路径。调用完毕后需要调用 `quit()` 方法关闭浏览器。
阅读全文