python爬虫-pyppeteer的基本使用

python爬虫-pyppeteer常用API

基本使用

安装
pip3 install pyppeteer
使用
```c
option = {'headless': False,
              'dumpio': True,# 减少内存消耗
              'autoClose': False,
              'ignoreDefaultArgs': ['--enable-automation'],
              'userDataDir': "./data/",
              'args': [
                  # '--window-size={1300},{800}',
                  '--start-maximized',  # 最大化窗口
                  # '--proxy-server=http://118.24.51.247:1443',  # 浏览器代理 配合某些中间人代理使用
                  # '--load-extension={}'.format(chrome_extension),  # 加载插件
                  # '--disable-extensions-except={}'.format(chrome_extension),
                  # '--disable-extensions',
                  '--hide-scrollbars',
                  '--disable-bundled-ppapi-flash',
                  '--mute-audio',
                  '--no-sandbox',  # 取消沙盒模式 沙盒模式下权限太小
                  '--no-sandbox',  # 不显示信息栏  比如 chrome正在受到自动测试软件的控制
                  '--disable-setuid-sandbox',
                  '--disable-gpu',
                  '--disable-infobars'
                  # log等级设置 在某些不是那么完整的系统里 如果使用默认的日志等级 可能会出现一大堆的warning信息
              ],
            }
browser = await launch(option)
# 创建一个页面对象, 页面操作在该对象上执行
page = await browser.newPage()
await page.setUserAgent(getRandomUserAgent())
await page.goto(url)


await page.close()
await browser.close()

常见使用

截屏
await page.screenshot({'path': "jd.jpg", 'fullPage': 'true'})
拖动页面元素
# 获取页面元素所在位置
btn_position = await page.evaluate('''
           () =>{
            return {
             x: document.querySelector('.shumei_captcha_slide_btn').getBoundingClientRect().x,
             y: document.querySelector('.shumei_captcha_slide_btn').getBoundingClientRect().y,
             width: document.querySelector('.shumei_captcha_slide_btn').getBoundingClientRect().width,
             height: document.querySelector('.shumei_captcha_slide_btn').getBoundingClientRect().height
             }}
            ''')

x = btn_position['x'] + btn_position['width'] / 2
y = btn_position['y'] + btn_position['height'] / 2

# 移动鼠标
await page.mouse.move(x, y)
# 按下
await page.mouse.down()
# 移动鼠标
await page.mouse.move(x + offset1, y, {'steps': 10})
# 抬起鼠标
await page.mouse.up()
获取文本
item_list = await page.xpath('//div[@class="card-info"]/div[@class="info"]/span[@class="info-number"]')

tempArr = []
for item in item_list:
    tempArr.append(await (await item.getProperty('textContent')).jsonValue())
获取URL
imageCard = ''
for imgItem in await page.xpath('//div[@class="author-container"]/div[@class="left"]/div/div/div/img'):
    imageCard = await (await imgItem.getProperty('src')).jsonValue()
获取链接
title_elements = await page.xpath('//div[@class="title-box"]/a')
for item in title_elements:
    title_link = await (await item.getProperty('href')).jsonValue()

常见错误

pyppeteer.errors.NetworkError: Protocol Error (Runtime.evaluate): Session closed. Most likely the page has been closed.
websockets降级到6.0会引发 pyppeteer 版本不兼容,安装8.1版本就行
pyppeteer.errors.NetworkError: Execution context was destroyed, most likely because of a navigation.
time.sleep()使用的问题
比如:
    time.sleep(2)
    print(await page.title())
解决:
    await asyncio.wait([
        page.content(),
        page.waitForNavigation({'timeout': 20000}),
    ])
    print(await page.title())
   
在浏览器无头模式下有时候会有各种问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值