我已经能够使用以下代码以某些元素的png形式捕获屏幕截图
from selenium import webdriver
from PIL import Image
from io import BytesIO
from os.path import expanduser
from time import sleep
# Define url and driver
url = 'https://www.formula1.com/'
driver = webdriver.Chrome('chromedriver')
# Go to url, scroll down to right point on page and find correct element
driver.get(url)
driver.execute_script('window.scrollTo(0, 4100)')
sleep(4) # Wait a little for page to load
element = driver.find_element_by_class_name('race-list')
location = element.location
size = element.size
png = driver.get_screenshot_as_png()
driver.quit()
# Store image as bytes, crop it and save to desktop
im = Image.open(BytesIO(png))
im = im.crop((200, 150, 700, 725))
path = expanduser('~/Desktop/')
im.save(path + 'F1-info.png')
这输出到:
我想要的是什么,但不是我想要的。我需要手动输入一些向下滚动的内容,由于找不到想要的元素(class='race step-1 step-2 step-3'
),我也不得不手动裁剪图像。
有更好的解决方案吗?
答案 0 :(得分:0)
以防有人怀疑。这就是我最后的管理方式。首先,我找到并滚动到页面右侧,就像这样
element = browser.find_element_by_css_selector('.race.step-1.step-2.step-3')
browser.execute_script('arguments[0].scrollIntoView()', element)
browser.execute_script('window.scrollBy(0, -80)')
然后裁剪图像
im = im.crop((200, 80, 700, 560))