我已经能够捕获截图作为一些元素的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'
)我不得不手动裁剪图像。
更好的解决方案?
万一有人在想。这就是我最终管理它的方式。首先,我发现并滚动到页面的右侧,就像这样
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))