Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ulixee
GitHub Repository: ulixee/secret-agent
Path: blob/main/examples/news.ycombinator.com.ts
1028 views
1
import agent, { Observable } from 'secret-agent';
2
3
// process.env.SA_SHOW_BROWSER = 'true';
4
5
async function run() {
6
await agent.configure({ userAgent: '~ chrome = 88' });
7
await agent.goto('https://news.ycombinator.com/');
8
await agent.waitForPaintingStable();
9
10
console.log('\n-- PRINTING location.href ---------');
11
console.log(await agent.url);
12
13
const stories = await agent.document.querySelectorAll('.athing');
14
let lastStory;
15
for (const story of stories) {
16
await agent.waitForMillis(200);
17
const extraElem = await story.nextElementSibling;
18
await agent.interact({
19
move: story,
20
});
21
const record = Observable({} as any);
22
agent.output.push(record);
23
24
const titleElem = await story.querySelector('a.storylink');
25
26
record.score = parseInt(
27
await extraElem.querySelector('.score').textContent.catch(() => '0'),
28
10,
29
);
30
record.id = await story.getAttribute('id');
31
record.age = await extraElem.querySelector('.age a').textContent;
32
record.title = await titleElem.textContent;
33
const contributor = await extraElem.querySelector('.hnuser').textContent.catch(() => '');
34
record.contributor = { id: contributor, username: contributor };
35
36
const links = [...(await extraElem.querySelectorAll('.subtext > a'))];
37
const commentsLink = links[links.length - 1];
38
const commentText = await commentsLink.textContent;
39
record.commentCount = commentText.includes('comment')
40
? parseInt(commentText.trim().match(/(\d+)\s/)[0], 10)
41
: 0;
42
43
lastStory = commentsLink;
44
record.url = await titleElem.getAttribute('href');
45
}
46
47
if (lastStory) {
48
await agent.click(lastStory);
49
await agent.waitForLocation('change');
50
await agent.waitForElement(agent.document.querySelector('textarea'));
51
await agent.click(agent.document.querySelector('textarea'));
52
await agent.type('Hackernews!');
53
const comments = [...(await agent.document.querySelectorAll('.commtext'))];
54
await agent.interact({
55
move: comments[comments.length - 1],
56
});
57
}
58
59
console.log('-- PRINTING extracted results ---------------');
60
console.log(agent.output);
61
62
console.log('-------------------------------------');
63
console.log('DONE');
64
65
await agent.close();
66
}
67
68
run().catch(error => console.log(error));
69
70