好久没用Pyppeteer自动化,今天稍微整理下分享给大家。
1.Pyppeteer是什么
说到Pyppeteer
得先说下Puppeteer
,Puppeteer
是谷歌官方出品的一个通过 DevTools
协议控制 headless Chrome
的 NodeJS
库。那Python版本就是Pyppeteer
不过需要注意的是:pyppeteer这个项目是非官方的。
虽然最新的提交代码是2020年5月8日,也不维护了,但是对于使用python的朋友们,还是可以尝试下。
功能:
- 基础功能
- 生成页面的截图和
PDF
- 自动提交表单,
UI
测试,键盘输入
- 生成页面的截图和
- 高级功能
JS
注入- 模拟操作
- 异步执行
- 用户伪装
2.安装方法
版本要求:Pyppeteer requires Python >= 3.6
python3 -m pip install pyppeteer
安装这个第三方库,会自动下载Chromium浏览器。
3. 官方小demo
import asyncio
from pyppeteer import launch
async def main():
browser = await launch()
page = await browser.newPage()
await page.goto('http://example.com')
await page.screenshot({'path': 'example.png'})
await browser.close()
asyncio.get_event_loop().run_until_complete(main())
做了如下动作:
打开Chromium浏览器,访问网站URL,截图保存为图片,关闭浏览器。
4. 实际会遇到的问题
- 问题1:打开浏览器窗口很大,内容显示很小
- 问题2:不想显示打开浏览器
- 问题3:想存储用户的数据在指定路径下。
- 问题4:不想显示
Chrome正受自动测试软件的控制。
- 问题5:某些网站需要访问proxy才可以打开,如何设置proxy?
- 问题6:如何暂停一会?
- 问题7: 如何在文本框输入,并回车
- 等等...
实际例子:
#!/usr/bin/python
# coding=utf-8
__author__ = 'testerzhang'
from loguru import logger
import asyncio
from pyppeteer import launch
logger.add('logs/record.log')
USER_DATA = './userdata'
def screen_size():
"""使用tkinter获取屏幕大小"""
# import tkinter
# tk = tkinter.Tk()
# width = tk.winfo_screenwidth()
# height = tk.winfo_screenheight()
# tk.quit()
width, height = 2048, 2048
return width, height
async def main():
width, height = screen_size()
browser = await launch(
{
'headless': True,
'userDataDir': USER_DATA,
'args': ['--disable-infobars', f'--window-size={width},{height}'],
}
)
page = await browser.newPage()
await page.setViewport({'width': width, 'height': height})
await page.goto('https://www.baidu.com')
dimensions = await page.evaluate('''() => {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight,
deviceScaleFactor: window.devicePixelRatio,
}
}''')
# {'width': 2048, 'height': 2048, 'deviceScaleFactor': 1}
logger.debug(dimensions)
await page.waitForSelector('input')
await page.type('input#kw.s_ipt', f'python')
# 点击提交按钮 click 通过selector点击指定的元素
# await page.click('input#su')
# 点击提交按钮 通过回车方式
await page.keyboard.press('Enter')
# 等待N秒显示结果
await asyncio.sleep(2)
# title_elements = await page.xpath('//h3[contains(@class,"t")]/a')
# for item in title_elements:
# title_str = await (await item.getProperty('textContent')).jsonValue()
# print(title_str)
content_elements = await page.xpath('//div[@class="c-container"]')
for item in content_elements:
content_str = await (await item.getProperty('textContent')).jsonValue()
logger.debug(f"内容={content_str}")
await page.screenshot({'path': 'pic/baidu_search.png'})
await browser.close()
asyncio.get_event_loop().run_until_complete(main())
5. 可能会有检测机制
比如你可以访问https://intoli.com/blog/not-possible-to-block-chrome-headless/chrome-headless-test.html
如果没调整代码,该网站会识别你是自动化软件。
可以稍微改下,比如增加特性:
await page.setUserAgent("Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5")
await page.evaluateOnNewDocument('() =>{ Object.defineProperties(navigator,'
'{ webdriver:{ get: () => false } }) }')
本文没有授权给任何组织、企业和个人转载,未经作者允许禁止转载!
欢迎关注我的公众号testerzhang,原创技术文章第一时间推送。