溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python爬蟲的pyppeteer庫怎么使用

發(fā)布時間:2022-03-29 16:30:15 來源:億速云 閱讀:315 作者:iii 欄目:移動開發(fā)

這篇文章主要介紹“python爬蟲的pyppeteer庫怎么使用”的相關(guān)知識,小編通過實(shí)際案例向大家展示操作過程,操作方法簡單快捷,實(shí)用性強(qiáng),希望這篇“python爬蟲的pyppeteer庫怎么使用”文章能幫助大家解決問題。

pyppeteer

介紹Pyppeteer之前先說一下Puppeteer,Puppeteer是谷歌出品的一款基于Node.js開發(fā)的一款工具,主要是用來操縱Chrome瀏覽器的 API,通過Javascript代碼來操縱Chrome瀏覽器,完成數(shù)據(jù)爬取、Web程序自動測試等任務(wù)。

pyppeteer 是非官方 Python 版本的 Puppeteer 庫,瀏覽器自動化庫,由日本工程師開發(fā)。

Puppeteer 是 Google 基于 Node.js 開發(fā)的工具,調(diào)用 Chrome 的 API,通過 JavaScript 代碼來操縱 Chrome 完成一些操作,用于網(wǎng)絡(luò)爬蟲、Web 程序自動測試等。

pyppeteer 使用了 Python 異步協(xié)程庫asyncio,可整合 Scrapy 進(jìn)行分布式爬蟲。

puppet 木偶,puppeteer 操縱木偶的人。

pyppeteer和puppeteer的不同點(diǎn)

pyppeteer支持字典和關(guān)鍵字傳參,puppeteer只支持字典傳參

# puppeteer支支持字典傳參
browser = await launch({"headless":True})

# pyppeteer支持字典和關(guān)鍵字傳參
browser = await launch({"headless":True})
browser = await launch(headless=True)

元素選擇器方法名$變?yōu)閝uerySelector

# puppeteer使用$符
page.$()/page.%%()/page.$x()
# pyppeteer使用python風(fēng)格的函數(shù)名
page.querySelector()/page.querySelectorAll()/page.xpath()

# 簡寫方式
page.J()/page.JJ()/page.Jx()

page.evluate()和page.querySelectorEval()的參數(shù)

puppeteer的evaluate()方法使用JavaScript原生函數(shù)或JavaScript表達(dá)式字符串。pyppeteer的evaluate()方法只使用JavaScript字符串,該字符串可以是函數(shù)也可以是表達(dá)式,pyppeteer會進(jìn)行自動判斷。但有時會判斷錯誤,如果字符串被判斷成了函數(shù),并且報錯,可以添加參數(shù)force_expr=True,強(qiáng)制pyppeteer作為表達(dá)式處理。

獲取網(wǎng)頁內(nèi)容:

content = await page.evaluate("document.body.textContent",force_expr=True)

獲取元素的內(nèi)部文字:

element = await page.querySelector("h1")
title = await page.evaluate("(element) => element.textContent",element)

安裝

1、安裝pyppeteer

pip install pyppeteer

2、安裝chromium

pyppeteer-install

簡單使用

import asyncio
from pyppeteer import launch

async def main():
    url = "https://www.toutiao.com/"
    # headless參數(shù)設(shè)置為Falase,則變成有頭模式
    browser = await launch(headless=False, ignoreDefaultArgs=["--enable-automation"])
    page = await browser.newPage()
    
    # 設(shè)置頁面視圖大小
    await page.setViewport(viewport={"width":1600,"herght":900})
    
    # 是否啟用JS,enabled設(shè)為False,則無渲染效果
    await page.setJavaScriptEnable(enabled=True)
    
    # 等待時間1000毫秒
    res = await page.goto(url,options={"timeout":1000})
    resp_headers = res.headers  # 響應(yīng)頭
    resp_status = res.status    # 響應(yīng)狀態(tài)
    
    # 等待
    await asyncio.sleep(2)
    await page.waitFor(1000)
    # 第二種方法 ,在while循環(huán)里強(qiáng)行查詢某元素進(jìn)行等待
    while not await page.querySelector(".t")
    
    # 滾動到頁面底部
    await page.evaluate("window.scrollBy(0,document.body.scrollHeight)")
    
    await page.screenshot({"path":"test.png"})
    
    # 打印網(wǎng)頁cookies
    print(await page.cookies())
    
    # 獲取所有html內(nèi)容
    print(await page.content())
    
    
    dimensions = await page.evaluate(pageFunction="""() => {
    		return {
    			width:document.documentElement.clentWidth,    // 頁面寬度
    			height:document.documentElement.clentHeight,  // 頁面高度
    			deviceScaleFactor: window.devicePixelRatio,  // 像素比1.0000000149011612
    			}
    		}""",force_expr=False)   # force_expr=False  執(zhí)行的是函數(shù)
    print(dimensions)
    
    content = await page.evaluate(pageFunction="document.body.textContent",force_expr=True)    # 只獲得文本 執(zhí)行js腳本,force_expr=True  執(zhí)行的是表達(dá)式
    print(content)
    
    # 打印當(dāng)前頁面的標(biāo)題
    print(await page.title())
    
    
    # 抓取新聞內(nèi)容  可以使用xpath表達(dá)式
    """
    pyppeteer 三種解析方式
    page.querySelector()
    page.querySelectorAll()
    page.xpath()
    簡寫方式為:
    page.J()
    page.JJ()
    page.Jx()
    """
    element = await page.querySelector(".feed-infinite-wrapper > ul>li")
    print(element)
    
    
    element = await page.querySelectorAll(".title-box a")
    for item in element:
        print(await item.getProperty("textContent"))
        # 獲取文本內(nèi)容
        title_str = await (await item.getProperty("textContent")).jsonValue()
        
        title_link = await (await item.getProperty("textContent")).jsonValue()
        
        # 獲取屬性值
        # title = await (await item.getProperty("class")).jsonValue()
        print(title_str,title_link)
    await browser.close()


asyncio.get_event_loop().run_until_complete(main())

模擬文本輸入和點(diǎn)擊

# 模擬輸入賬號密碼 參數(shù){"delay":reand_int()}  延遲輸入時間
await page.type("#kw","百度",delay=100)
await page.type("#TPL_username_1","asdasd")

await page.waitFor(1000)
await page.click("#su")

移除Chrome正受到自動測試軟件的控制

browser = await launch(headless=False, ignoreDefaultArgs=["--enable-automation"])
# 添加ignoreDefaultArgs=["--enable-automation"] 參數(shù)

爬取京東商城

from bs4 import BeautifulSoup
from pyppeteer import launch
import asyncio


def screen_size():
    return 1600,900


async def main(url):
    browser = await launch({"args":["--no-sandbox"],}) # "headless":False
    page = await browser.newPage()
    width, height = screen_size()
    await page.setViewport(viewport={"width":width,"height":height})
    await page.setJavaScriptEnabled(enabled=True)
    await page.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36")
    await page.goto(url)

    await page.evaluate("window.scrollBy(0, document.body.scrollHeight)")

    await asyncio.sleep(1)

    # content = await page.content()
    li_list = await page.xpath("//*[@id="J_goodsList"]/ul/li")

    item_list = []
    for li in li_list:
        a = await li.xpath(".//div[@class="p-img"]/a")
        detail_url = await (await a[0].getProperty("href")).jsonValue()
        promo_words = await (await a[0].getProperty("title")).jsonValue()
        a_ = await li.xpath(".//div[@class="p-commit"]/strong/a")
        p_commit = await (await a_[0].getProperty("textContent")).jsonValue()
        i = await li.xpath("./div/div[3]/strong/i")
        price = await (await i[0].getProperty("textContent")).jsonValue()
        em = await li.xpath("./div/div[4]/a/em")
        title = await (await em[0].getProperty("textContent")).jsonValue()
        item = {
            "title" : title,
            "detail_url" : detail_url,
            "promp_words" : promo_words,
            "p_commit" : p_commit,
            "price" : price
        }
        item_list.append(item)

    await page_close(browser)
    return item_list


async def page_close(browser):
    for _page in await browser.pages():
        await _page.close()
    await browser.close()


url = "https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&wq="
		"%E6%89%8B%E6%9C%BA&pvid=e07184578b8442c58ddd65b221020e99&page={}&s=56&click=0 "
task_list = []
for i in range(1,4):
    page = i * 2 - 1
    task_list.append(main(url.format(page)))

results = asyncio.get_event_loop().run_until_complete(asyncio.gather(*task_list))

for i in results:
    print(i,len(i))

print("*"*100)

python爬蟲的pyppeteer庫怎么使用

關(guān)于“python爬蟲的pyppeteer庫怎么使用”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點(diǎn)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI