如何用pyppeteer获取数据,模拟登陆?
安装环境
python3 -m pip install pyppeteer
https://github.com/miyakogi/pyppeteer
02
hello world!
#引用相关的库
import asyncio
from pyppeteer import launch
async def main():
browser = await launch()
page = await browser.newPage()
#想爬取哪个页面,修改对应的url即可,
#注意timeout的设置,因为有时候网速比较慢,可以把超时的时间设得久一点。
await page.goto('https://getgetai.com',{"timeout":3*60000})
#screenshot是截屏的命令,path设置截屏后的图片保存路径跟名称
#await page.screenshot({'path': 'example.png'})
#evaluate是注入js到url的页面里,需要具备js的相关知识
result = await page.evaluate('''() => {
//获得网页的标题
var res=document.title
//把结果返回给python
return res
}''')
#打印返回的结果
print(result)
await browser.close()
#main是异步执行的,需要用这行代码来执行,而不是直接main()
asyncio.get_event_loop().run_until_complete(main())
获取数据,通过研究网页的接口请求方式
https://www.todaytix.com/x/london/shows
https://api.todaytix.com/views/v2/heroList?location=2&fieldset=HeroSuperEssentials
async function postData() {
var _url = "https://api.todaytix.com/views/v2/heroList?location=2&fieldset=HeroSuperEssentials";
return new Promise(function (resolve, reject) {
fetch(_url, {
method: 'GET',
mode: 'cors',
})
.then(response => response.json())
.then(data => {
resolve(data);
});
})
};
import asyncio
from pyppeteer import launch
async def main():
browser = await launch()
page = await browser.newPage()
await page.goto('https://www.todaytix.com/x/london/shows',{"timeout":3*60000})
result = await page.evaluate('''async () => {
async function postData() {
var _url = "https://api.todaytix.com/views/v2/heroList?location=2&fieldset=HeroSuperEssentials";
return new Promise(function (resolve, reject) {
fetch(_url, {
method: 'GET',
mode: 'cors',
})
.then(response => response.json())
.then(data => {
resolve(data);
});
})
};
var res=await postData()
return res
}''')
print(result)
await browser.close()
asyncio.get_event_loop().run_until_complete(main())
模拟登陆,以印象笔记为例
import asyncio
from pyppeteer import launch
async def main():
user_name='your username'
pass_word='your password'
#无头模式关闭
browser = await launch({'headless': False})
page = await browser.newPage()
await page.goto('https://app.yinxiang.com/Login.action',{"timeout":14*60000})
await page.type("#username",user_name)
await page.click("#loginButton")
await page.waitFor(3000)
await page.type("#password",pass_word)
await page.click("#loginButton")
result = await page.evaluate('''() => {
var res=document.title
return res
}''')
print(result)
#await browser.close()
asyncio.get_event_loop().run_until_complete(main())