这里写自定义目录标题
学习pyppeteer-练习(一)
实现打开百度页面,获取“百度一下”点击按钮,和输入框对象,在输入框中输入“测试工程师”,点击搜索。抓取搜索结果中的链接。
代码实现如下:
#coding:utf-8
import os ,time , asyncio ,tkinter
from pyppeteer import launch
def screen_size():#设置页面大小
tk = tkinter.Tk()
width = tk.winfo_screenwidth()
height = tk.winfo_screenheight()
tk.quit()
return {'width':width,'height':height}
async def get_baidu():
browser = await launch()#devtools=True 调试模式 headless = False,
# userDataDir (str): 即用户数据文件夹,即可以保留一些个性化配置和操作记录。
page = await browser.newPage()
await page.setViewport(screen_size())
await page.goto("https://www.baidu.com/")#打开百度url
element = (await page.xpath('//*[@id="su"]'))[0]#定位“百度一下”按钮
value1 = await (await element.getProperty('value')).jsonValue()#获取元素内部的值
print(value1)#输出:百度一下
await page.type('#kw','测试工程师')#在输入框填充内容
await element.click() # 点击搜索按钮
await asyncio.sleep(5.0)
for num in range(1,100):
selector = "//*[@id='{0}']/h3/a".format(num)#每个结果中对应的xpath
# print(selector)
element = await page.xpath(selector)
# print(element)
if element == [] :
continue
href = await (await element[0].getProperty('href')).jsonValue()#获取元素内部的href参数值
print(href)
loop = asyncio.get_event_loop()
loop.run_until_complete(get_baidu())
# loop.close()
输出结果:
百度一下
http://www.baidu.com/link?url=Q0bGayl9Mye_mW2bLjQmbNKn6eKK7CcKwJDq6fYOBqlBIQ3mHCcqzI07uscFWy4lHzGT3TfMistNMjt7ZeuMzB2HVHE2-PCSJeQV-TMjOwJXLfP22bT8JW5ySL0oHbXPNMj7AJUkbUp8wGgRYEZGyq
http://www.baidu.com/link?url=091LTH7QWo8ijmItJ4MoXWGz7E6zFn3KSjLcQ1z9ZJITn7Uq4v9M6pqViaJbp0Ha
http://www.baidu.com/link?url=PXvkrPqQguil2mbRRe96mfstqpvXyIBq6QlkgwqKPO22abInxgRsWEBIwNL5F7cXa-Ek3RRAynokA3azo9YVjK
http://www.baidu.com/link?url=V4bmSLxKea6peu_16ZQ7OIbHjw_pkjFJIx5pbley-jXN2iwbPpU92rPbvGhSrtX-okUTnXKvXUn4inLa2ygAeK
http://www.baidu.com/link?url=6ydgpuLsiq-fkLztoALLoQnA8jtFeGGciq0ERfYimb0DdszZD5StBob7lABp3r1v
http://www.baidu.com/link?url=VtQw38fFcRNpnP3olVcwopgeeJeaolbjhKj4_vTHgYG-gOJOcdzGwCOfs6gp_9ac
http://www.baidu.com/link?url=QYv4evtPOIBPg1suGFljHenkvjoXdDnYQHtrWSp1kkJsf4dHVdUSj-Gk_6zcqGrIsOhoScY4hwyRJNCxX_8aO8jyT7mvJxFo-JO4kPtxHHm
http://www.baidu.com/link?url=LMwEG6c0jJXNPReuqr0NQMAr1ha0GN22aHPrh9_egkkgawAeXWQMp4jFS-xPKksE
http://www.baidu.com/link?url=ejlV2HESD4QcKSeP0Ty2yf6DPsKvk97vB5Dj151nP-VhVZFwW9q8Yp5rV_N14nZXDq-VuNB1z8gQGTbhH5u84IfGB2DJYXhJCKfzO4jeq3a
Process finished with exit code 0