內容說明
本文主要基於ChromeDriver實現模擬手機UI截圖功能,完整項目結構請參考
https://blog.csdn.net/lylfv/article/details/106874925
測試環境
- CentOS 7
- Python 3
- Chrome & ChromeDriver
Chrome 瀏覽器安裝
- 編輯repo文件
cd /etc/yum.repos.d/
vim google-chrome.repo
內容如下:
[google-chrome]
name=google-chrome
baseurl=http://dl.google.com/linux/chrome/rpm/stable/x86_64
enabled=1
gpgcheck=1
gpgkey=https://dl.google.com/linux/linux_signing_key.pub
- 安裝命令
yum -y install google-chrome-stable --nogpgcheck
- 查看版本
google-chrome --version
ChromeDriver下載&配置
unzip chromedriver_linux64.zip
mv chromedriver /usr/bin/
chmod 755 /usr/bin/chromedriver
代碼詳情
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
def capture_screen():
# 打開瀏覽器並登陸
mobileEmulation = {'deviceName': 'Galaxy S5'}
options = webdriver.ChromeOptions()
options.add_experimental_option('mobileEmulation', mobileEmulation)
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-gpu')
browser = webdriver.Chrome(executable_path="/usr/bin/chromedriver", options=options)
browser.get('https://www.baidu.com/')
browser.save_screenshot('screen.png')
browser.quit()
if __name__ == "__main__":
capture_screen()
輸出結果
- 保存上述代碼爲ui_test.py
- 當前目錄運行命令
python3 ui_test.py
生成screen.png文件