python爬蟲(chóng)之pyppeteer庫(kù)簡(jiǎn)單使用
pyppeteer
介紹Pyppeteer之前先說(shuō)一下Puppeteer,Puppeteer是谷歌出品的一款基于Node.js開(kāi)發(fā)的一款工具,主要是用來(lái)操縱Chrome瀏覽器的 API,通過(guò)Javascript代碼來(lái)操縱Chrome瀏覽器,完成數(shù)據(jù)爬取、Web程序自動(dòng)測(cè)試等任務(wù)。
pyppeteer 是非官方 Python 版本的 Puppeteer 庫(kù),瀏覽器自動(dòng)化庫(kù),由日本工程師開(kāi)發(fā)。
Puppeteer 是 Google 基于 Node.js 開(kāi)發(fā)的工具,調(diào)用 Chrome 的 API,通過(guò) JavaScript 代碼來(lái)操縱 Chrome 完成一些操作,用于網(wǎng)絡(luò)爬蟲(chóng)、Web 程序自動(dòng)測(cè)試等。
pyppeteer 使用了 Python 異步協(xié)程庫(kù)asyncio,可整合 Scrapy 進(jìn)行分布式爬蟲(chóng)。
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() # 簡(jiǎn)寫(xiě)方式 page.J()/page.JJ()/page.Jx()
page.evluate()和page.querySelectorEval()的參數(shù)
puppeteer的evaluate()方法使用JavaScript原生函數(shù)或JavaScript表達(dá)式字符串。pyppeteer的evaluate()方法只使用JavaScript字符串,該字符串可以是函數(shù)也可以是表達(dá)式,pyppeteer會(huì)進(jìn)行自動(dòng)判斷。但有時(shí)會(huì)判斷錯(cuò)誤,如果字符串被判斷成了函數(shù),并且報(bào)錯(cuò),可以添加參數(shù)force_expr=True
,強(qiáng)制pyppeteer作為表達(dá)式處理。
獲取網(wǎng)頁(yè)內(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
簡(jiǎn)單使用
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è)置頁(yè)面視圖大小 await page.setViewport(viewport={'width':1600,'herght':900}) # 是否啟用JS,enabled設(shè)為False,則無(wú)渲染效果 await page.setJavaScriptEnable(enabled=True) # 等待時(shí)間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)行查詢(xún)某元素進(jìn)行等待 while not await page.querySelector('.t') # 滾動(dòng)到頁(yè)面底部 await page.evaluate('window.scrollBy(0,document.body.scrollHeight)') await page.screenshot({'path':'test.png'}) # 打印網(wǎng)頁(yè)cookies print(await page.cookies()) # 獲取所有html內(nèi)容 print(await page.content()) dimensions = await page.evaluate(pageFunction='''() => { return { width:document.documentElement.clentWidth, // 頁(yè)面寬度 height:document.documentElement.clentHeight, // 頁(yè)面高度 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)前頁(yè)面的標(biāo)題 print(await page.title()) # 抓取新聞內(nèi)容 可以使用xpath表達(dá)式 ''' pyppeteer 三種解析方式 page.querySelector() page.querySelectorAll() page.xpath() 簡(jiǎn)寫(xiě)方式為: 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)擊
# 模擬輸入賬號(hào)密碼 參數(shù){'delay':reand_int()} 延遲輸入時(shí)間 await page.type('#kw',"百度",delay=100) await page.type('#TPL_username_1',"asdasd") await page.waitFor(1000) await page.click('#su')
移除Chrome正受到自動(dòng)測(cè)試軟件的控制
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)
到此這篇關(guān)于python爬蟲(chóng)之pyppeteer庫(kù)的文章就介紹到這了,更多相關(guān)python爬蟲(chóng)pyppeteer庫(kù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決Python paramiko 模塊遠(yuǎn)程執(zhí)行ssh 命令 nohup 不生效的問(wèn)題
這篇文章主要介紹了解決Python paramiko 模塊遠(yuǎn)程執(zhí)行ssh 命令 nohup 不生效的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07Python 創(chuàng)建TCP服務(wù)器的方法
這篇文章主要介紹了Python 創(chuàng)建TCP服務(wù)器的方法,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-07-07python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5控件數(shù)據(jù)拖曳Drag與Drop詳細(xì)使用方法與實(shí)例
這篇文章主要介紹了python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5控件數(shù)據(jù)拖曳Drag與Drop詳細(xì)使用方法與實(shí)例,需要的朋友可以參考下2020-02-02python爬蟲(chóng)xpath模塊簡(jiǎn)介示例代碼
xpath是最常用且最便捷高效的一種解析方式,通用型強(qiáng),其不僅可以用于python語(yǔ)言中,還可以用于其他語(yǔ)言中,數(shù)據(jù)解析建議首先xpath,這篇文章主要介紹了python爬蟲(chóng)xpath模塊簡(jiǎn)介,需要的朋友可以參考下2023-02-02Pytest執(zhí)行unittest TestSuite(測(cè)試套件)的實(shí)現(xiàn)方法
TestSuite一直是unittest的靈活與精髓之處,在繁多的測(cè)試用例中,可以任意挑選和組合各種用例集,這篇文章主要介紹了Pytest執(zhí)行unittest TestSuite(測(cè)試套件)的實(shí)現(xiàn)方法,需要的朋友可以參考下2021-08-08