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
联系客服