如何使用selenium python从网站下载图像

2024-10-02 00:37:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想下载一个特定地区的网站截图.png。我试图定义元素,但python给了我以下错误:


回溯(最近一次呼叫最后一次): 文件“C:/Users/gribe/PycharmProjects/pythonProject/main.py”,第25行,在 元素=驱动程序。通过元素id(“highcharts-43”)查找元素 文件“C:\Users\gribe\PycharmProjects\pythonProject\venv\lib\site packages\selenium\webdriver\remote\webdriver.py”,第360行,按id查找元素 返回self.find_元素(by=by.ID,value=ID_u) 文件“C:\Users\gribe\PycharmProjects\pythonProject\venv\lib\site packages\selenium\webdriver\remote\webdriver.py”,第976行,在find\u元素中 返回self.execute(Command.FIND_元素{ 文件“C:\Users\gribe\PycharmProjects\pythonProject\venv\lib\site packages\selenium\webdriver\remote\webdriver.py”,第321行,执行 self.error\u handler.check\u响应(响应) 文件“C:\Users\gribe\PycharmProjects\pythonProject\venv\lib\site packages\selenium\webdriver\remote\errorhandler.py”,第242行,在check\u响应中 引发异常类(消息、屏幕、堆栈跟踪) selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法定位元素:{“方法”:“css选择器”,“选择器”:“[id=”highcharts-43“]” (会话信息:chrome=85.0.4183.121)


从网站上我研究了图表位置和id,但这还不够。你能给我一些关于这个话题的建议吗


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from PIL import Image
from io import BytesIO

element = driver.find_element_by_id('highcharts-43')
location = element.location
size = element.size
print(location)
print(size)
#
png = driver.get_screenshot_as_png()
im = Image.open(BytesIO(png)) # uses PIL library to open image in memory

left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']


im = im.crop((left, top, right, bottom)) # defines crop points
im.save('screenshot.png') # saves new cropped image

多谢各位


Tags: 文件frompyimportid元素sizepng

热门问题