一.render的使用
from requests_html import HTMLSession
session =HTMLSession()
response = session.get('https://www.cnblogs.com/guapitomjoy/')
print(response.html.render())
- 進行js注入
- 模擬人操作瀏覽器
二.render的參數
1.script(str)
執行的js代碼
語法:response.html.render(script='js代碼字符串格式')
2.scrolldown(int)
- 滑動滑塊
- 和sleep聯用為多久滑動一次
- 每次滾動一頁
語法:response.html.render(scrolldown=頁面向下滾動的次數)
3.retries(int)
加載頁面失敗的次數
4.wait(float)
加載頁面的等待時間(秒),防止超時(可選)
5.sleep(int)
在頁面初次渲染之后的等待時間
6.timeout(int or float)
頁面加載時間上線
7.keep_page(bool)
如果為真,允許你用r.html.page訪問頁面
8.reload(bool)
如果為假,那么頁面不會從瀏覽器中加載,而是從內存中加載
三.r.html.page與瀏覽器交互
1.基本語法
from requests_html import HTMLSession
session =HTMLSession()
response = session.get('https://www.cnblogs.com/guapitomjoy/')
print(response.html.render(keep_page=true))
async def run():
#交互語句
await r.html.page.XXX
try:
session.loop.run_until_complete(run())
finally:
session.close()
2.鍵盤事件
- keyboard.down('鍵盤名稱'):按下鍵盤不彈起(與鍵盤有點不太down('h')只會出現一個h而不是hhhhhhh....)
- keyboard.up('鍵盤名稱'):抬起按鍵
- keyboard.press('鍵盤名稱'):按下+彈起
- keyboard.type('輸入的字符串內容',{‘delay’:100}) delay為每個子輸入后延遲時間單位為
ms
3.鼠標事件
點擊
- click('css選擇器',{ 'button':'left', 'clickCount':1,'delay':0})
- button為鼠標的按鍵
left
,right
, ormiddle
, - clickCount:點擊次數默認次數為1
- delay:點擊延遲時間,單位是毫秒
- button為鼠標的按鍵
- mouse.click(x, y,{ 'button':'left', 'clickCount':1,'delay':0})
- x,y:muber數據類型,代表點擊對象的坐標
點下去不抬起
- mouse.down({'button':xxx,clickCount:xxx})
抬起鼠標
- mouse.up({'button':xxx,clickCount:xxx})
4.其他
等待
- waitFor('選擇器, 方法 或者 超時時間')
- 選擇器: css 選擇器或者一個xpath 根據是不是
//
開頭 - 方法:時候此方法是page.waitForFunction()的簡寫
- 超時時間:單位毫秒
- 選擇器: css 選擇器或者一個xpath 根據是不是
等待元素加載
waitForSelector('css選擇器')
獲取x,y坐標
mydic =await r.html.page.evaluate('''() =>{
var a = document.querySelector('#kw') #對象的css選擇器
var b = a.getBoundingClientRect()
return {'x':b.x,'y':b.y , 'width':b.width , 'height':b.height }
}''')
執行js代碼
evaluate('js代碼字符串格式')
輸入內容
type('css選擇器',’內容‘,{’delay‘:100})
聚焦
focus('css選擇器')
移動到
hover('css選擇器')
獲取cookies
cookies()
設置頁面大小
setViewport({'width': 1366, 'height': 768})
截圖
screenshot({'path':保存本地路徑,'clip':{'x':1,'y':1,'width':100,'height':100}})
- x:圖片的x坐標
- y:圖片的y坐標
- width: 圖片寬
- height:圖片高