Last active
March 1, 2026 21:24
-
-
Save KhaledHawwas/a1cdd070c7bbe07bc8476c609938d0ab to your computer and use it in GitHub Desktop.
freelancer jobs extraction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import requests | |
| from bs4 import BeautifulSoup | |
| import csv | |
| import sys | |
| # Crawleo API configuration | |
| API_KEY = "YOUR API KEY"#todo: replace with your Crawleo API key | |
| # https://www.crawleo.dev/ | |
| API_ENDPOINT = "https://api.crawleo.dev/crawl" | |
| base_url = "https://www.freelancer.com/jobs/android" | |
| total_pages = 3 | |
| def crawl_with_crawleo(url, output_format="markdown"): | |
| """ | |
| Crawl a URL using Crawleo API | |
| Args: | |
| url: The URL to crawl | |
| output_format: Format of the output (markdown, html, text) | |
| Returns: | |
| The crawled content | |
| """ | |
| headers = { | |
| "Authorization": f"Bearer {API_KEY}" | |
| } | |
| params = { | |
| "urls": url, | |
| "output_format": output_format | |
| } | |
| try: | |
| response = requests.get(API_ENDPOINT, headers=headers, params=params) | |
| response.raise_for_status() | |
| return response.json() | |
| except requests.exceptions.RequestException as e: | |
| print(f"Error crawling {url}: {e}") | |
| return None | |
| def extract_job_details(job): | |
| """ | |
| Extract all relevant details from a single job element | |
| Args: | |
| job: BeautifulSoup element representing a job card | |
| Returns: | |
| Dictionary containing job details | |
| """ | |
| # Title and Link | |
| title_elem = job.find("a", class_="JobSearchCard-primary-heading-link") | |
| title = title_elem.text.strip() if title_elem else "No Title" | |
| link = title_elem.get('href', "No Link") | |
| full_link = f"https://www.freelancer.com{link}" if link.startswith("/") else link | |
| # Days Left | |
| days_elem = job.find("span", class_="JobSearchCard-primary-heading-days") | |
| days_left = days_elem.text.strip() if days_elem else "N/A" | |
| # Description | |
| desc_elem = job.find("p", class_="JobSearchCard-primary-description") | |
| description = desc_elem.text.strip() if desc_elem else "No Description" | |
| # Price | |
| price = "N/A" | |
| # Try secondary price first (often used in desktop view) | |
| price_elem = job.find("div", class_="JobSearchCard-secondary-price") | |
| if not price_elem: | |
| price_elem = job.find("div", class_="JobSearchCard-primary-price") | |
| if price_elem: | |
| # Clean up price text (remove "Avg Bid" label if present) | |
| price_text = price_elem.get_text(separator=' ', strip=True) | |
| price = price_text.replace("(Avg Bid)", "").strip() | |
| # Bids | |
| bids_elem = job.find("div", class_="JobSearchCard-secondary-entry") | |
| bids = bids_elem.text.strip() if bids_elem else "0 bids" | |
| # Tags | |
| tags_container = job.find("div", class_="JobSearchCard-primary-tags") | |
| tags = [] | |
| if tags_container: | |
| tags = [t.text.strip() for t in tags_container.find_all("a")] | |
| return { | |
| 'Title': title, | |
| 'URL': full_link, | |
| 'Price': price, | |
| 'Bids': bids, | |
| 'Time': days_left, | |
| 'Tags': ', '.join(tags), | |
| 'Description': description | |
| } | |
| def print_job_details(job_data, index): | |
| """ | |
| Print job details to console in a formatted way | |
| Args: | |
| job_data: Dictionary containing job details | |
| index: Job number for display | |
| """ | |
| print(f"--- Job {index} ---") | |
| print(f"Title: {job_data['Title']}") | |
| print(f"URL: {job_data['URL']}") | |
| print(f"Price: {job_data['Price']}") | |
| print(f"Bids: {job_data['Bids']}") | |
| print(f"Time: {job_data['Time']}") | |
| print(f"Tags: {job_data['Tags']}") | |
| description = job_data['Description'] | |
| if len(description) > 150: | |
| print(f"Description: {description[:150]}...") | |
| else: | |
| print(f"Description: {description}") | |
| print() | |
| def save_jobs_to_csv(jobs_data, filename='freelancer_jobs.csv'): | |
| """ | |
| Save job data to a CSV file | |
| Args: | |
| jobs_data: List of dictionaries containing job details | |
| filename: Name of the CSV file to create | |
| Returns: | |
| True if successful, False otherwise | |
| """ | |
| if not jobs_data: | |
| print("\nNo jobs data to save.") | |
| return False | |
| try: | |
| with open(filename, 'w', newline='', encoding='utf-8') as csvfile: | |
| fieldnames = ['Title', 'URL', 'Price', 'Bids', 'Time', 'Tags', 'Description'] | |
| writer = csv.DictWriter(csvfile, fieldnames=fieldnames) | |
| writer.writeheader() | |
| writer.writerows(jobs_data) | |
| print(f"\nโ Successfully saved {len(jobs_data)} jobs to '{filename}'") | |
| return True | |
| except Exception as e: | |
| print(f"\nError saving to CSV: {e}") | |
| return False | |
| def parse_html_content(html_content): | |
| """ | |
| Parse HTML content and extract all job listings | |
| Args: | |
| html_content: Raw HTML string from the crawled page | |
| Returns: | |
| List of dictionaries containing job details | |
| """ | |
| soup = BeautifulSoup(html_content, 'html.parser') | |
| # Extract job count from project-list | |
| project_list = soup.find('div', id='project-list') | |
| if not project_list: | |
| print("\nProject list 'project-list' not found.") | |
| return [] | |
| jobs = [child for child in project_list.children if child.name] | |
| print(f"\nFound {len(jobs)} jobs in project-list. Extracting details...\n") | |
| # Collect job data | |
| jobs_data = [] | |
| for idx, job in enumerate(jobs, 1): | |
| job_data = extract_job_details(job) | |
| jobs_data.append(job_data) | |
| print_job_details(job_data, idx) | |
| return jobs_data | |
| def crawl_page(base_url, page_number): | |
| """ | |
| Crawl a single page and extract job data | |
| Args: | |
| base_url: Base URL for the job listings (e.g., "https://www.freelancer.com/jobs/android") | |
| page_number: Page number to crawl | |
| Returns: | |
| List of job dictionaries, or empty list if crawling failed | |
| """ | |
| # Construct URL for the specific page | |
| if page_number == 1: | |
| url = base_url | |
| else: | |
| url = f"{base_url}/{page_number}" | |
| print(f"\n{'='*60}") | |
| print(f"Crawling page {page_number}: {url}") | |
| print(f"{'='*60}") | |
| result = crawl_with_crawleo(url, output_format="raw_html") | |
| if not result: | |
| print(f"Failed to crawl page {page_number}") | |
| return [] | |
| # Extract content from Crawleo API response | |
| data = result.get('data', {}) | |
| results_list = data.get('results', []) | |
| if not isinstance(results_list, list) or len(results_list) == 0: | |
| print(f"\nNo content found for page {page_number}. Check API response structure.") | |
| if 'status' in result: | |
| print(f"Status: {result.get('status')}") | |
| return [] | |
| if 'content' not in results_list[0]: | |
| print(f"\nNo content found for page {page_number}.") | |
| return [] | |
| html_content = results_list[0]['content'] | |
| # Parse HTML and extract job data | |
| jobs_data = parse_html_content(html_content) | |
| return jobs_data | |
| def main(): | |
| """ | |
| Main function to orchestrate the web crawling and data extraction process | |
| Crawls all 7 pages of Android jobs | |
| """ | |
| # Force UTF-8 encoding for stdout to handle special characters | |
| sys.stdout.reconfigure(encoding='utf-8') | |
| # Collect all jobs from all pages | |
| all_jobs = [] | |
| print(f"\n๐ Starting to crawl {total_pages} pages of Android jobs...") | |
| for page_num in range(1, total_pages + 1): | |
| jobs_data = crawl_page(base_url, page_num) | |
| if jobs_data: | |
| all_jobs.extend(jobs_data) | |
| print(f"โ Page {page_num}: Extracted {len(jobs_data)} jobs (Total so far: {len(all_jobs)})") | |
| else: | |
| print(f"โ Page {page_num}: No jobs found") | |
| # Save all jobs to CSV | |
| print(f"\n{'='*60}") | |
| print(f"๐ CRAWLING SUMMARY") | |
| print(f"{'='*60}") | |
| print(f"Total pages crawled: {total_pages}") | |
| print(f"Total jobs extracted: {len(all_jobs)}") | |
| if all_jobs: | |
| save_jobs_to_csv(all_jobs) | |
| else: | |
| print("\nโ No jobs data collected from any page.") | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment