One, involving knowledge points
- How to use css selector
- Common elements get
- $ Element selection
- type (api input)
- click (api click)
Second, learning website
Third, the environment
- node js
- puppeteer
- Editor vscode
Fourth, examples
- Common selector element
Selector | Examples | Explanation |
id selector | #id | Id matching selected elements, there is only one |
class selector | .class | A plurality of elements while matching the class |
Attribute selectors | div [could] | Matching property has attr, regardless of his value |
Attribute selectors | div [attr = '122'] | Matching attributes attr having a value of 122 |
Descendant selectors | div span | Descendant selector matches all subsequent div span tags, separated by spaces and span div |
Child element selector | div > span | All span after sub-element selector, matching div |
Match n th element of the parent element | div:nth-child(2) | The second matching element of the parent element |
1. id selector
Examples of URL: https://www.cnblogs.com/
Code demonstrates:
const puppeteer = require('puppeteer'); (async () => { const brower = await puppeteer.launch({ executablePath:'D:\\wangxiao\\chrome-win\\chrome-win\\chrome.exe', headless:false }); const page = await brower.newPage(); await page.goto('https://www.cnblogs.com/'); const input = await page.$('#zzk_q'); input.type('12222'); //await brower.close(); })().catch(error =>{console.log('error')});
2.nth-child(n) 灵活运用
这里不一一演示了,演示主要的,比如子级,如图,我们想登入,但是登入没有id,也没有class, 那我们试试其他方式,往父级看,
有唯一id = 'span_userinfo' ,那么我们可以手写成
获取所有的a标签 - >
element = '#span_userinfo a'
获取登入的超级链接
element = '#span_userinfo a:nth-child(1)'
我们代码验证一下对不对
const puppeteer = require('puppeteer'); (async () => { const brower = await puppeteer.launch({ executablePath:'D:\\wangxiao\\chrome-win\\chrome-win\\chrome.exe', headless:false }); const page = await brower.newPage(); await page.goto('https://www.cnblogs.com/'); await page.click('#span_userinfo a:nth-child(1)') //await brower.close(); })().catch(error =>{console.log('error')});