-
Notifications
You must be signed in to change notification settings - Fork 0
/
scraper.go
289 lines (220 loc) · 6.63 KB
/
scraper.go
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
package main
import (
// "encoding/csv"
"context"
"fmt"
"log"
"os"
"regexp"
"time"
"github.com/chromedp/chromedp"
"github.com/gocolly/colly"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type Job struct {
Title string `bson:"title"`
Company string `bson:"company"`
Location string `bson:"location"`
}
func main() {
var newJobPostings []Job;
// ------ SCRAPE FROM DISCORD ---------
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file: %s", err)
}
fmt.Println("Scrape from discord servers")
opt := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.Flag("headless", false),
)
allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opt...)
defer cancel()
ctx, cancel := chromedp.NewContext(allocCtx)
defer cancel()
ctx, cancel = context.WithTimeout(ctx, time.Duration(300)*time.Second)
defer cancel()
discordSource := getDiscord(ctx)
readDiscordHTML(discordSource)
listJobs := readDiscordHTML(discordSource)
defer chromedp.Cancel(ctx)
// ------- SET UP MONGODB --------
// Get keys from dotenv
uri := os.Getenv("MONGO_URI")
// Use the SetServerAPIOptions() method to set the version of the Stable API on the client
serverAPI := options.ServerAPI(options.ServerAPIVersion1)
opts := options.Client().ApplyURI(uri).SetServerAPIOptions(serverAPI)
// Create a new client and connect to the server
client, err := mongo.Connect(context.TODO(), opts)
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
// Send a ping to confirm a successful connection
if err := client.Database("admin").RunCommand(context.TODO(), bson.D{{"ping", 1}}).Err(); err != nil {
panic(err)
}
fmt.Println("Successfully connected to MongoDB!")
// Create collection
var dbName = "jobDatabase"
var collectionName = "jobs"
collection := client.Database(dbName).Collection(collectionName)
for _, s := range listJobs {
if len(s) <= 2 {
continue
}
newJob := Job {
Company: s,
Location: "US",
Title: "Software Engineer Intern",
}
exists, err := jobExists(client, collection, newJob)
if err != nil {
log.Fatal("Error in checking job existence:", err)
}
if exists {
fmt.Println("Job already exist, skipping")
} else {
_, err := collection.InsertOne(context.Background(), newJob)
if err != nil {
log.Printf("Failed to insert job into MongoDB: %v", err)
} else {
fmt.Println("Job added to the database successfully!")
}
newJobPostings = append(newJobPostings, newJob)
}
}
// ----- SCRAPE FROM GITHUB --------
c := colly.NewCollector()
c.OnRequest(func(r *colly.Request) {fmt.Println("Scraping:", r.URL)})
c.OnResponse(func(r *colly.Response) {fmt.Println("Status:", r.StatusCode)})
c.OnHTML("table > tbody", func(h *colly.HTMLElement) {
count := 0
h.ForEach("tr", func(_ int, el *colly.HTMLElement) {
if count > 20 {
return
}
company := el.ChildText("td:nth-child(1)")
title := el.ChildText("td:nth-child(2)")
location := el.ChildText("td:nth-child(3)")
newJob := Job{
Title: title,
Company: company,
Location: location,
}
// Check if the job already exists in the database
exists, err := jobExists(client, collection, newJob)
if err != nil {
log.Fatal("Error checking job existence:", err)
}
if exists {
fmt.Println("Job already exist, skipping")
} else {
// JobPostings = append(JobPostings, newJob)
_, err := collection.InsertOne(context.Background(), newJob)
if err != nil {
log.Printf("Failed to insert job into MongoDB: %v", err)
} else {
fmt.Println("Job added to the database successfully!")
}
newJobPostings = append(newJobPostings, newJob)
}
count ++
})})
c.OnError(func(r *colly.Response, err error) {
fmt.Println("Request URL:", r.Request.URL, "failed with response:", r, "\nError:", err)
})
c.Visit("https://github.com/SimplifyJobs/Summer2024-Internships")
emailSending(newJobPostings)
}
func jobExists(client *mongo.Client, collection *mongo.Collection, job Job) (bool, error) {
// Define filter criteria to find a job by company and title
filter := bson.M{"company": job.Company, "title": job.Title}
// Execute a find one operation
var result Job
err := collection.FindOne(context.Background(), filter).Decode(&result)
if err != nil {
if err == mongo.ErrNoDocuments {
// Job not found
return false, nil
}
// Other error occurred
return false, err
}
// Job found
return true, nil
}
func getDiscord(ctx context.Context) string {
var discordSource string
discordChannelUrl := "https://discord.com/channels/698366411864670250/1118750128266825768"
discordUsername := os.Getenv("DISCORD_USERNAME")
discordPass := os.Getenv("DISCORD_PASS")
discordScrollUp := 10
err := chromedp.Run(ctx,
chromedp.Navigate("https://discord.com/channels/@me"),
)
if err != nil {
log.Fatal(err)
}
time.Sleep(3 * time.Second)
err = chromedp.Run(ctx,
chromedp.SendKeys(`//input[@name="email"]`, discordUsername, chromedp.BySearch),
chromedp.SendKeys(`//input[@name="password"]`, discordPass, chromedp.BySearch),
chromedp.Click(`//button[@type="submit"]`, chromedp.BySearch),
)
if err != nil {
log.Fatal((err))
}
fmt.Println("Log in successfully")
if err != nil {
log.Fatal("Error logging in:", err)
}
time.Sleep(3 * time.Second)
err = chromedp.Run(ctx,
chromedp.Navigate(discordChannelUrl),
chromedp.WaitVisible(`body`),
)
if err != nil {
log.Fatal("Error entering channel:", err)
}
time.Sleep(4 * time.Second)
fmt.Println("Enter channel successfully ")
for i :=0; i < discordScrollUp; i++ {
err := chromedp.Run(ctx,
chromedp.ScrollIntoView(`//ol/li[1]`, chromedp.BySearch),
)
if err != nil {
log.Fatal("Error scrolling:", err)
}
time.Sleep(1 * time.Second)
}
fmt.Println("Take tags successfully")
err = chromedp.Run(ctx,
chromedp.TextContent(`//ol`, &discordSource, chromedp.BySearch),
)
if err != nil {
log.Fatal(err)
}
time.Sleep(3 * time.Second)
// fmt.Println(discordSource)
return discordSource
}
func readDiscordHTML(discordSource string) []string {
listJobs := []string{}
pattern := `\!process ([a-zA-Z]*)`
re := regexp.MustCompile(pattern)
matches := re.FindAllStringSubmatch(discordSource, -1)
for _, match := range matches {
if len(match) > 1 && match[1] != "Company" {
listJobs = append(listJobs, match[1])
}
}
// fmt.Println(listJobs)
return listJobs
}