pyppeteer的使用


pyppeteer的使用

安裝

  • 屬於第三方模塊進行安裝. pip install pyppeteer

  • 在Linux中,如果權限不夠則加上. sudo pip install pyppeteer

使用

使用今日頭條作為demo

from pyppeteer import launch
import asyncio

async def main(timeout=30):# 設定時間超時, 默認是30秒
   # async 用來申明一個函數是一個異步函數
   browser = await launch(headless=True, args=["--no-sandbox"])
   # 參數說明:
   # headless 參數設為False,變為有頭模式
   # Pyppeteer 支持字典和關鍵字傳遞參數
   page = await browser.newPage()
   
   # 設置頁面大小
   await page.setViewport(viewport={"width":1280, "height":800})
   
   # 是否啟用JS, enabled設為False,則無渲染效果
   await page.setJavaScriptEnabled(enabled=True)
   
   # 超時時間設置
   res = await page.goto(url=url, options={"timeout":1000})
   # 響應頭
   resp_headers = res.headers
   # 響應狀態
   resp_status = res.status
   
   # 等待
   await asynico.sleep(2)
   # 第二種方法
   while not await page.querySelector(".t"):
       pass
   
   # 滾動到頁面底部
   await page.evaluate('windows.scrollBy(0,document.body.scrollHeight)')
   
   # 截圖報存圖片
   await page.screenshot({"path": "toutiao.png"})
   
   # 獲取cookie
   print(await page.cookies())  
   
   # 打印頁面文本信息
   print(await page.content())
   
   # 在頁面上執行js腳本
   dimensions = await page.evaluate(pageFunction='''() => {
          return {
              width: document.documentElement.clientWidth, // 頁面寬度
              height: document.documentElement.clientHeight, // 頁面高度
              deviceScaleFactor: window.devicePixelRatio, // 像素比 1.0000000149011612
          }
      }''', force_expr=False)  # force_expr=False 執行的是函數
   print(dimensions)
   # 只獲取文本 執行 js 腳本 force_expr 為 True 則執行的是表達式
   content = await page.evaluate(pageFunction='document.body.textContent', force_expr=True)
   print(content)

   # 打印當前頁標題
   print(await page.title())\
   
   # 抓取其他信息
   """
  1.選擇器, Page.querySelector()
  2.選擇器, Page.querySelectorAll()
  3.xpath表達式, Page.xpath()
  """
   # 使用querySelector()
   element = await page.querySelector(".feed-infinite-wrapper > ul>li") # 只抓取一個
   print(element)
   
   # 獲取所有的文本信息, 執行js代碼
   content = await page.querySelectorAll('(element) => element.textContent', element)
   print(content)
   
   # 使用xpath
   # elements = await page.xpath('//div[@class="title-box"]/a')
   # 使用選擇器全選
   elements = await page.querySelectorAll(".title-box a")
   for item in elements:
       print(await item.getProperty("textContent"))
       # 獲取文本信息
       title = await (await item.getProperty("textContent")).jsonValue()
       # 獲取連接
       link = await (await item.getProperty("href")).jsonValue()
       print(title)  
       print(link)
   # 關閉瀏覽器
   await browser.close()  
  • 如何啟動程序

  • 1.創建一個event_loop對象

       loop = asyncio.get_event_loop()
  • 2.啟動運行

       loop.run_until_complete(main())

模擬鍵盤輸入

# 模擬輸入 賬號密碼 {'delay': rand_int()} 為輸入時間
   await page.type('#TPL_username_1', "sadfasdfasdf")
   await page.type('#TPL_password_1', "123456789", )
   
   await page.waitFor(1000)
   await page.click("#J_SubmitStatic")
使用tkinter獲取頁面高度寬度
def screen_size():
   """使用tkinter獲取屏幕大小"""
   import tkinter
   tk = tkinter.Tk()
   width = tk.winfo_screenwidth()
   height = tk.winfo_screenheight()
   tk.quit()
   return width, height
針對iframe操作
  • page.frames獲取所有的iframe列表,需要判斷操作的是哪一個iframe跟操作page一樣

from pyppeteer import launch
import asyncio

async def main(url):
   w = await launch({"headless":False, "args":["--no-sandbox"]})
   page = await w.newPage()
   await page.setViewport({"width":1366, "height":800})
   await page.goto(url)
   try:
       await asyncio.sleep(1)
       frame = page.frames
       print(frame)
       
       title = await frame[1].title()
       print(title)
       
       await asyncio.sleep(1)
       login = await frame[1].querySelector('#switcher_plogin')
       print(login)
       
       await login.click()
       await asyncio.sleep(5)
   except Exception as e:
       print(e)
   for page in await w.pages():
       await page.close()
   await w.close()

asyncio.get_event_loop().run_until_complete(main("https://i.qq.com/?rd=1"))
# asyncio.get_event_loop().run_until_complete(main("https://www.gushici.com/"))

大部分借鑒與別人,目前覺得模擬器爬蟲還是比較慢的,靜待大家的創新。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM