-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunc.ts
More file actions
74 lines (72 loc) · 2.62 KB
/
Copy pathfunc.ts
File metadata and controls
74 lines (72 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { chromium, BrowserContext, Page } from 'playwright'
import path from 'path'
import os from 'os'
import inquirer from 'inquirer' // 引入 inquirer
import { BROWSER_CONFIGS, LAUNCH_OPTIONS } from './constants'
/**
* @description: 启动浏览器
* @return {BrowserContext} 浏览器上下文
*/
export async function startBrowser(): Promise<BrowserContext> {
// 选择浏览器
const { browserChoice } = await inquirer.prompt([
{
type: 'list',
name: 'browserChoice',
message: '请选择要使用的浏览器:',
choices: [
{ name: 'Microsoft Edge', value: 'edge' },
{ name: 'Google Chrome', value: 'chrome' },
],
// 默认选项
default: 'edge',
},
])
// 获取浏览器配置
const selectedConfig = BROWSER_CONFIGS[browserChoice as keyof typeof BROWSER_CONFIGS]
console.log(`正在启动 ${browserChoice.toUpperCase()} 浏览器...`)
// 启动浏览器
const context: BrowserContext = await chromium.launchPersistentContext(selectedConfig.userDataDir, {
...LAUNCH_OPTIONS,
channel: selectedConfig.channel as 'msedge' | 'chrome' | undefined,
})
console.log('浏览器启动成功')
return context
}
/**
* @description: 阅读排序第一的帖子
* @param {BrowserContext} context
* @return {PageObject} 页面对象
* @note:
*/
export async function readFirstTopic(context: BrowserContext): Promise<Page | undefined> {
try {
// 获取页面实例
const page: Page = context.pages().length ? context.pages()[0] : await context.newPage()
// 直接访问未读页面
await page.goto('https://linux.do/unseen')
// 找到 class 为 topic-list-body 的元素 如果该元素存在 则说明页面已经加载完毕
const postStreamLocator = page.locator('.topic-list-body')
// 等待元素可见,并设置一个合理的超时
await postStreamLocator.waitFor({ state: 'visible', timeout: 15000 })
console.log('未读页面加载完毕')
// 阅读排序第一的帖子 topic-list-body 下的第一个 tr 元素
const firstTrLocator = postStreamLocator.locator('tr:nth-child(1)')
const firstRowCount = await firstTrLocator.count()
if (firstRowCount === 0) {
console.log('未读列表为空,稍后再来吧')
return undefined
}
// 高亮 一下 方便观察
await firstTrLocator.highlight()
await page.waitForTimeout(1000)
// 找到 link 元素
const linkLocator = firstTrLocator.locator('.raw-link')
await linkLocator.click()
console.log('进入第一个帖子')
return page
} catch (error) {
console.error('脚本执行失败:', error)
return undefined
}
}