feat: implement multiple new job crawlers and add corresponding test suites
This commit is contained in:
@@ -0,0 +1,285 @@
|
||||
package amazon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/hireme/hireme/internal/crawler"
|
||||
"github.com/hireme/hireme/internal/logger"
|
||||
)
|
||||
|
||||
type AmazonCrawler struct {
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func NewAmazonCrawler() *AmazonCrawler {
|
||||
return NewAmazonCrawlerWithClient(&http.Client{
|
||||
Timeout: 30 * time.Second,
|
||||
})
|
||||
}
|
||||
|
||||
func NewAmazonCrawlerWithClient(client *http.Client) *AmazonCrawler {
|
||||
return &AmazonCrawler{
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *AmazonCrawler) CanHandle(platform string) bool {
|
||||
p := strings.ToLower(platform)
|
||||
return p == "amazon" || p == "aws" || strings.Contains(p, "amazon.jobs")
|
||||
}
|
||||
|
||||
type amazonSearchResponse struct {
|
||||
Hits int `json:"hits"`
|
||||
Jobs []amazonJobItem `json:"jobs"`
|
||||
}
|
||||
|
||||
type amazonJobItem struct {
|
||||
ID string `json:"id"`
|
||||
IDIsp string `json:"id_icims"`
|
||||
Title string `json:"title"`
|
||||
Company string `json:"company_name"`
|
||||
Location string `json:"location"`
|
||||
City string `json:"city"`
|
||||
State string `json:"state"`
|
||||
Country string `json:"country_code"`
|
||||
JobPath string `json:"job_path"`
|
||||
Description string `json:"description"`
|
||||
BasicQualifications string `json:"basic_qualifications"`
|
||||
PreferredQuals string `json:"preferred_qualifications"`
|
||||
JobCategory string `json:"job_category"`
|
||||
JobFamily string `json:"job_family_name"`
|
||||
PostedDate string `json:"posted_date"`
|
||||
}
|
||||
|
||||
func (c *AmazonCrawler) DiscoverJobs(ctx context.Context, targetURL string) ([]crawler.DiscoveredJob, error) {
|
||||
seen := make(map[string]bool)
|
||||
var discovered []crawler.DiscoveredJob
|
||||
|
||||
searchAPI := targetURL
|
||||
if !strings.Contains(searchAPI, "search.json") {
|
||||
u, err := url.Parse(targetURL)
|
||||
if err == nil && u.Host != "" {
|
||||
q := u.Query()
|
||||
searchAPI = fmt.Sprintf("https://www.amazon.jobs/en/search.json?%s", q.Encode())
|
||||
} else {
|
||||
searchAPI = fmt.Sprintf("https://www.amazon.jobs/en/search.json?base_query=%s&loc_query=Seattle%%2C+WA%%2C+USA", url.QueryEscape(targetURL))
|
||||
}
|
||||
}
|
||||
|
||||
resultLimit := 100
|
||||
for page := 0; page < 5; page++ {
|
||||
offset := page * resultLimit
|
||||
reqURL := searchAPI
|
||||
if strings.Contains(reqURL, "?") {
|
||||
reqURL = fmt.Sprintf("%s&result_limit=%d&offset=%d", searchAPI, resultLimit, offset)
|
||||
} else {
|
||||
reqURL = fmt.Sprintf("%s?result_limit=%d&offset=%d", searchAPI, resultLimit, offset)
|
||||
}
|
||||
|
||||
body, err := c.fetchURL(ctx, reqURL)
|
||||
if err != nil {
|
||||
if page == 0 {
|
||||
return nil, err
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
var resp amazonSearchResponse
|
||||
if err := json.Unmarshal([]byte(body), &resp); err != nil {
|
||||
if page == 0 {
|
||||
return nil, fmt.Errorf("failed to parse Amazon search response: %w", err)
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
if len(resp.Jobs) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
newFound := false
|
||||
for _, job := range resp.Jobs {
|
||||
jobID := job.ID
|
||||
if jobID == "" {
|
||||
jobID = job.IDIsp
|
||||
}
|
||||
if jobID == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
applyURL := fmt.Sprintf("https://www.amazon.jobs/en/jobs/%s", jobID)
|
||||
if job.JobPath != "" {
|
||||
if strings.HasPrefix(job.JobPath, "http") {
|
||||
applyURL = job.JobPath
|
||||
} else {
|
||||
applyURL = "https://www.amazon.jobs" + job.JobPath
|
||||
}
|
||||
}
|
||||
|
||||
if !seen[applyURL] {
|
||||
seen[applyURL] = true
|
||||
newFound = true
|
||||
discovered = append(discovered, crawler.DiscoveredJob{
|
||||
CanonicalID: fmt.Sprintf("amazon:%s", jobID),
|
||||
ApplyURL: applyURL,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if !newFound || len(resp.Jobs) < resultLimit {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
logger.Log.Infow("Amazon discovery finished", "found_count", len(discovered))
|
||||
return discovered, nil
|
||||
}
|
||||
|
||||
func (c *AmazonCrawler) FetchJobDetail(ctx context.Context, applyURL string) (*crawler.ExtractedJob, error) {
|
||||
jobID := parseAmazonJobID(applyURL)
|
||||
if jobID == "" {
|
||||
jobID = fmt.Sprintf("%x", sha256.Sum256([]byte(applyURL)))[:16]
|
||||
}
|
||||
|
||||
jsonURL := fmt.Sprintf("https://www.amazon.jobs/en/jobs/%s.json", jobID)
|
||||
body, err := c.fetchURL(ctx, jsonURL)
|
||||
if err == nil && json.Valid([]byte(body)) {
|
||||
var detail struct {
|
||||
Job amazonJobItem `json:"job"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &detail); err == nil && detail.Job.Title != "" {
|
||||
j := detail.Job
|
||||
var sb strings.Builder
|
||||
if j.Description != "" {
|
||||
sb.WriteString("## Description\n\n")
|
||||
sb.WriteString(cleanHTML(j.Description))
|
||||
sb.WriteString("\n\n")
|
||||
}
|
||||
if j.BasicQualifications != "" {
|
||||
sb.WriteString("## Basic Qualifications\n\n")
|
||||
sb.WriteString(cleanHTML(j.BasicQualifications))
|
||||
sb.WriteString("\n\n")
|
||||
}
|
||||
if j.PreferredQuals != "" {
|
||||
sb.WriteString("## Preferred Qualifications\n\n")
|
||||
sb.WriteString(cleanHTML(j.PreferredQuals))
|
||||
sb.WriteString("\n\n")
|
||||
}
|
||||
|
||||
company := "Amazon"
|
||||
if j.Company != "" {
|
||||
company = j.Company
|
||||
}
|
||||
loc := j.Location
|
||||
if loc == "" && j.City != "" {
|
||||
loc = fmt.Sprintf("%s, %s, %s", j.City, j.State, j.Country)
|
||||
}
|
||||
if loc == "" {
|
||||
loc = "Seattle, WA, USA"
|
||||
}
|
||||
|
||||
return &crawler.ExtractedJob{
|
||||
CanonicalID: fmt.Sprintf("amazon:%s", jobID),
|
||||
Title: j.Title,
|
||||
Company: company,
|
||||
Location: loc,
|
||||
ApplyURL: applyURL,
|
||||
RawContent: sb.String(),
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
htmlBody, err := c.fetchURL(ctx, applyURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
title := extractRegex(htmlBody, `<h1[^>]*class="[^"]*title[^"]*"[^>]*>(.*?)</h1>`)
|
||||
if title == "" {
|
||||
title = extractRegex(htmlBody, `<h1[^>]*>(.*?)</h1>`)
|
||||
}
|
||||
if title == "" {
|
||||
title = "Software Engineer - Amazon"
|
||||
}
|
||||
|
||||
return &crawler.ExtractedJob{
|
||||
CanonicalID: fmt.Sprintf("amazon:%s", jobID),
|
||||
Title: cleanHTML(title),
|
||||
Company: "Amazon",
|
||||
Location: "Seattle, WA, USA",
|
||||
ApplyURL: applyURL,
|
||||
RawContent: cleanHTML(htmlBody),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *AmazonCrawler) fetchURL(ctx context.Context, urlStr string) (string, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", urlStr, nil)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
|
||||
req.Header.Set("Accept", "application/json, text/html, */*")
|
||||
|
||||
resp, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("HTTP GET failed: %w", err)
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("HTTP GET returned status %d for %s", resp.StatusCode, urlStr)
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read response: %w", err)
|
||||
}
|
||||
|
||||
return string(body), nil
|
||||
}
|
||||
|
||||
func parseAmazonJobID(u string) string {
|
||||
re := regexp.MustCompile(`/jobs/([0-9A-Za-z\-]+)`)
|
||||
m := re.FindStringSubmatch(u)
|
||||
if len(m) >= 2 {
|
||||
return strings.TrimSuffix(m[1], ".json")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func extractRegex(s, pattern string) string {
|
||||
re := regexp.MustCompile(pattern)
|
||||
m := re.FindStringSubmatch(s)
|
||||
if len(m) >= 2 {
|
||||
return m[1]
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func cleanHTML(s string) string {
|
||||
s = strings.ReplaceAll(s, "<b>", "**")
|
||||
s = strings.ReplaceAll(s, "</b>", "**")
|
||||
s = strings.ReplaceAll(s, "<strong>", "**")
|
||||
s = strings.ReplaceAll(s, "</strong>", "**")
|
||||
s = strings.ReplaceAll(s, "<br>", "\n")
|
||||
s = strings.ReplaceAll(s, "<br/>", "\n")
|
||||
s = strings.ReplaceAll(s, "<br />", "\n")
|
||||
s = strings.ReplaceAll(s, "<li>", "- ")
|
||||
s = strings.ReplaceAll(s, "</li>", "\n")
|
||||
s = strings.ReplaceAll(s, "<ul>", "\n")
|
||||
s = strings.ReplaceAll(s, "</ul>", "\n")
|
||||
s = strings.ReplaceAll(s, "<p>", "\n")
|
||||
s = strings.ReplaceAll(s, "</p>", "\n")
|
||||
reTags := regexp.MustCompile(`<[^>]*>`)
|
||||
s = reTags.ReplaceAllString(s, "")
|
||||
return strings.TrimSpace(s)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package amazon
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hireme/hireme/internal/crawler/crawlertest"
|
||||
)
|
||||
|
||||
type roundTripFunc func(req *http.Request) *http.Response
|
||||
|
||||
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
return f(req), nil
|
||||
}
|
||||
|
||||
func TestAmazonCrawler_DiscoverAndFetch(t *testing.T) {
|
||||
mockClient := &http.Client{
|
||||
Transport: roundTripFunc(func(r *http.Request) *http.Response {
|
||||
if strings.Contains(r.URL.Path, "search.json") {
|
||||
body := `{
|
||||
"hits": 1,
|
||||
"jobs": [
|
||||
{
|
||||
"id": "2500123",
|
||||
"title": "Software Development Engineer II - AWS",
|
||||
"company_name": "Amazon Web Services, Inc.",
|
||||
"city": "Seattle",
|
||||
"state": "WA",
|
||||
"country_code": "USA",
|
||||
"job_path": "/en/jobs/2500123/software-development-engineer-ii-aws"
|
||||
}
|
||||
]
|
||||
}`
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Body: io.NopCloser(bytes.NewBufferString(body)),
|
||||
Header: make(http.Header),
|
||||
}
|
||||
}
|
||||
|
||||
if strings.Contains(r.URL.Path, "2500123.json") {
|
||||
body := `{
|
||||
"job": {
|
||||
"id": "2500123",
|
||||
"title": "Software Development Engineer II - AWS",
|
||||
"company_name": "Amazon Web Services, Inc.",
|
||||
"location": "Seattle, WA, USA",
|
||||
"description": "<p>Come build the future of cloud computing.</p>",
|
||||
"basic_qualifications": "<li>3+ years of non-internship professional software development experience</li>",
|
||||
"preferred_qualifications": "<li>Experience with distributed systems and Go/Java/C++</li>"
|
||||
}
|
||||
}`
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Body: io.NopCloser(bytes.NewBufferString(body)),
|
||||
Header: make(http.Header),
|
||||
}
|
||||
}
|
||||
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusNotFound,
|
||||
Body: io.NopCloser(bytes.NewBufferString("not found")),
|
||||
Header: make(http.Header),
|
||||
}
|
||||
}),
|
||||
}
|
||||
|
||||
c := NewAmazonCrawlerWithClient(mockClient)
|
||||
if !c.CanHandle("amazon") || !c.CanHandle("aws") {
|
||||
t.Errorf("CanHandle should support amazon and aws")
|
||||
}
|
||||
|
||||
discovered, err := c.DiscoverJobs(context.Background(), "https://www.amazon.jobs/en/search.json?base_query=Software+Engineer")
|
||||
if err != nil {
|
||||
t.Fatalf("DiscoverJobs failed: %v", err)
|
||||
}
|
||||
|
||||
if len(discovered) != 1 {
|
||||
t.Fatalf("expected 1 discovered job, got %d", len(discovered))
|
||||
}
|
||||
|
||||
if discovered[0].CanonicalID != "amazon:2500123" {
|
||||
t.Errorf("unexpected canonical ID: %s", discovered[0].CanonicalID)
|
||||
}
|
||||
|
||||
extracted, err := c.FetchJobDetail(context.Background(), "https://www.amazon.jobs/en/jobs/2500123")
|
||||
if err != nil {
|
||||
t.Fatalf("FetchJobDetail failed: %v", err)
|
||||
}
|
||||
|
||||
if extracted.Title != "Software Development Engineer II - AWS" {
|
||||
t.Errorf("unexpected title: %s", extracted.Title)
|
||||
}
|
||||
if extracted.Company != "Amazon Web Services, Inc." {
|
||||
t.Errorf("unexpected company: %s", extracted.Company)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAmazonCrawler_LiveIntegration(t *testing.T) {
|
||||
crawlertest.RunLiveIntegration(t, crawlertest.LiveTestConfig{
|
||||
PlatformName: "Amazon",
|
||||
Crawler: NewAmazonCrawler(),
|
||||
TargetURL: "https://www.amazon.jobs/en/search.json?base_query=Software+Development+Engineer&loc_query=Seattle%2C+WA%2C+USA",
|
||||
ExpectedCanonicalPrefix: "amazon:",
|
||||
ExpectedCompany: "Amazon",
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user