pyppeteer的基本使用发放

基本步骤

import asyncio
import os

from pyppeteer import launch


async def main():
    browser = await launch({'headless': False},args=['--disable-infobars', '--window-size=1920,1080'])
    page = await browser.newPage()
    #需要二次设置,只在开头args设置没有用处
    await page.setViewport({'width': 1920, 'height': 1080})
    await page.goto('http://quotes.toscrape.com/js/')
    await asyncio.sleep(10)
    # 生成截图
    await page.screenshot(path='1.png')
    # 生成pdf文件,只能在无头模式下用,可显示状态会报错
    # await page.pdf(path='1.pdf')
	# 'node => node.innerText' 为固定参数
    line = await page.querySelectorEval('body > div > div:nth-child(5) > span','node => node.innerText')
    
    # 批量属性值  获取所有满足条件的href List
    href = await page.querySelectorAllEval('#s-top-left > a', 'nodes => nodes.map(node => node.href)')
    # 批量文本值  获取所有满足条件的text List
    text = await page.querySelectorAllEval('#s-top-left > a', 'nodes => nodes.map(node => node.innerText)')

    line = line.split('Harry')[-1]
    # line = await page.querySelectorEval('body > div > div:nth-child(5) > span.text')
    print(type(line),line)
    if os.path.exists('my_data'):
        os.mkdir('my_data')
    with open('my_data/111.txt','w',encoding='utf-8') as file:
        file.write(line)

    await browser.close()


asyncio.get_event_loop().run_until_complete(main())
浏览器的配置信息
browser = await launch(
	headless=False,
	# 默认状态下为true
    # headless=True,
     timeout=1500,
     # 开发者工具
     devtools=False,
     # 防止浏览器卡住
     dumpio=True,
     # 设置用户文件夹,默认cookie会存放这里
     userDataDir='./userdata',
     options={'args':
                 [
				#关闭沙盒模式,linux下需要使用
                  '--no-sandbox',
                   # 关闭提示条
                   '--disable-infobars',
                   f'--window-size={width},{height}',
                   '--disable-extensions',
                   '--hide-scrollbars',
                   '--disable-bundled-ppapi-flash',
                   '--mute-audio',
                   '--disable-setuid-sandbox',
                   '--disable-gpu',
                 ],
             }
)
page = await browser.newPage()
# 设置UA,ua列表自己设置,或者使用faker
await page.setUserAgent(random.choice(self.user_agent))
# 异步等待
await asyncio.sleep(3)
# 点击操作
page.click("#Submit")
# 输入字符串
page.type('#Submit','aaaaaaaaaa')
# 让当前页面滑动到最底部
await page.evaluate('window.scrollBy(0, document.body.scrollHeight)')

参考链接:
https://cuiqingcai.com/6942.html
https://blog.csdn.net/Aaron_liu1/article/details/107328140

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值