In this web scraping tutorial, we'll take a look at how to scrape job listing data from Indeed.com.
Indeed.com is one of the most popular job listing websites, and it's pretty easy to scrape!
In this tutorial, we'll build our scraper with just a few lines of Python code. We'll take a look at how Indeed's search works to replicate it in our scraper and extract job data from embedded javascript variables. Let's dive in!
For this web scraper, we'll only need an HTTP client library such as httpx library, which can be installed through pip console command:
$ pip install httpx
There are many HTTP clients in Python like requests, httpx, aiohttp, etc. however, we recommend httpx as it's the least one likely to be blocked as it supports http2 protocol. httpx also supports asynchronous python, which means we can scrape really fast!
For ScrapFly users, we'll also be providing code versions using scrapfly-sdk.
To start, let's take a look at how we can find job listings on Indeed.com.
If we go to the homepage and submit our search, we can see that Indeed redirects us to a search URL with a few key parameters:
0:00
/
https://www.indeed.com/jobs?q=python&l=Texas
So, to find Python jobs in Texas, all we have to do is send a request with l=Texas and q=Python URL parameters:
from scrapfly import ScrapflyClient, ScrapeConfig
scrapfly = ScrapflyClient(key="YOUR SCRAPFLY KEY")
result = scrapfly.scrape(ScrapeConfig(
url="https://www.indeed.com/jobs?q=python&l=Texas",
asp=True,
))
print(result.selector.xpath('//h1').get())
Note: if you receive response status code 403 here, it's likely you are being blocked, see Avoiding Blocking section below for more information.
We got a single page that contains 15 job listings! Before we collect the remaining pages, let's see how we can parse job listing data from this response.
We could parse the HTML document using CSS or XPath selectors, but there's an easier way: we can find all of the job listing data hidden away deep in the HTML as a JSON document:
So, instead, let's parse this data using a simple regular expression pattern:
import re
import json
import os
from scrapfly import ScrapflyClient, ScrapeConfig
scrapfly = ScrapflyClient(os.environ["SCRAPFLY_KEY"])
def parse_search_page(html: str):
data = re.findall(r'window.mosaic.providerData\["mosaic-provider-jobcards"\]=(\{.+?\});', html)
data = json.loads(data[0])
return {
"results": data["metaData"]["mosaicProviderJobCardsModel"]["results"],
"meta": data["metaData"]["mosaicProviderJobCardsModel"]["tierSummaries"],
}
result = scrapfly.scrape(
ScrapeConfig(
url="https://www.indeed.com/jobs?q=python&l=Texas",
asp=True,
)
)
print(parse_search_page(result.content))
In our code above, we are using a regular expression pattern to select mosaic-provider-jobcards variable value, load it as a python dictionary and parse out the result and paging meta-data.
Now that we have the first page results and total page count, we can retrieve the remaining pages:
Python
ScrapFly
import asyncio
import json
import re
from urllib.parse import urlencode
import httpx
def parse_search_page(html: str):
data = re.findall(r'window.mosaic.providerData\["mosaic-provider-jobcards"\]=(\{.+?\});', html)
data = json.loads(data[0])
return {
"results": data["metaData"]["mosaicProviderJobCardsModel"]["results"],
"meta": data["metaData"]["mosaicProviderJobCardsModel"]["tierSummaries"],
}
async def scrape_search(client: httpx.AsyncClient, query: str, location: str, max_results: int = 50):
def make_page_url(offset):
parameters = {"q": query, "l": location, "filter": 0, "start": offset}
return "https://www.indeed.com/jobs?" + urlencode(parameters)
print(f"scraping first page of search: {query=}, {location=}")
response_first_page = await client.get(make_page_url(0))
data_first_page = parse_search_page(response_first_page.text)
results = data_first_page["results"]
total_results = sum(category["jobCount"] for category in data_first_page["meta"])
# there's a page limit on indeed.com of 1000 results per search
if total_results > max_results:
total_results = max_results
print(f"scraping remaining {total_results - 10 / 10} pages")
other_pages = [make_page_url(offset) for offset in range(10, total_results + 10, 10)]
for response in await asyncio.gather(*[client.get(url=url) for url in other_pages]):
results.extend(parse_search_page(response.text))
return results
import json
import re
from urllib.parse import urlencode
from scrapfly import ScrapflyClient, ScrapeConfig
scrapfly = ScrapflyClient(key="YOUR SCRAPFLY KEY")
def parse_search_page(html: str):
data = re.findall(r'window.mosaic.providerData\["mosaic-provider-jobcards"\]=(\{.+?\});', html)
data = json.loads(data[0])
return {
"results": data["metaData"]["mosaicProviderJobCardsModel"]["results"],
"meta": data["metaData"]["mosaicProviderJobCardsModel"]["tierSummaries"],
}
async def scrape_search(query: str, location: str, max_results: int = 50):
def make_page_url(offset):
parameters = {"q": query, "l": location, "filter": 0, "start": offset}
return "https://www.indeed.com/jobs?" + urlencode(parameters)
print(f"scraping first page of search: {query=}, {location=}")
result_first_page = await scrapfly.async_scrape(ScrapeConfig(make_page_url(0), asp=True))
data_first_page = parse_search_page(result_first_page.content)
results = data_first_page["results"]
total_results = sum(category["jobCount"] for category in data_first_page["meta"])
# there's a page limit on indeed.com of 1000 results per search
if total_results > max_results:
total_results = max_results
print(f"scraping remaining {total_results - 10 / 10} pages")
other_pages = [
ScrapeConfig(make_page_url(offset), asp=True)
for offset in range(10, total_results + 10, 10)
]
async for result in scrapfly.concurrent_scrape(other_pages):
results.extend(parse_search_page(result.content))
return results
# example run
import asyncio
asyncio.run(scrape_search(query="python", location="texas"))
Run Code & Example Output
async def main():
# we need to use browser-like headers to avoid being blocked instantly:
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36",
"Accept-Encoding": "gzip, deflate, br",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9,lt;q=0.8,et;q=0.7,de;q=0.6",
}
async with httpx.AsyncClient(headers=HEADERS) as client:
search_data = await scrape_search(client, query="python", location="texas")
print(json.dumps(search_data, indent=2))
asyncio.run(main())
This will result in search result data similar to:
We've successfully scraped mountains of data with very few lines of Python code! Next, let's take a look at how to get the remainder of the job listing details (like full description) by scraping job pages.
Scraping Indeed Jobs
Our search results contain almost all job listing data except a few details, such as a complete job description. To scrape this, we need the job id, which is found in the jobkey field in our search results:
{
"jobkey": "a82cf0bd2092efa3",
}
Using jobkey we can request the full job details page, and just like with the search; we can parse the embedded data instead of the HTML:
We can see that all of the job and page information is hidden in the _initialData variable, which we can extract with a simple regular expression pattern:
Python
ScrapFly
import re
import json
import asyncio
from typing import List
import httpx
def parse_job_page(html):
"""parse job data from job listing page"""
data = re.findall(r"_initialData=(\{.+?\});", html)
data = json.loads(data[0])
return data["jobInfoWrapperModel"]["jobInfoModel"]
async def scrape_jobs(client: httpx.AsyncClient, job_keys: List[str]):
"""scrape job details from job page for given job keys"""
urls = [f"https://www.indeed.com/m/basecamp/viewjob?viewtype=embedded&jk={job_key}" for job_key in job_keys]
scraped = []
for response in await asyncio.gather(*[client.get(url=url) for url in urls]):
scraped.append(parse_job_page(response.text))
return scraped
import re
import json
from typing import List
from scrapfly import ScrapeConfig, ScrapflyClient
scrapfly = ScrapflyClient(key="YOUR SCRAPFLY KEY")
def parse_job_page(html):
"""parse job data from job listing page"""
data = re.findall(r"_initialData=(\{.+?\});", html)
data = json.loads(data[0])
return data["jobInfoWrapperModel"]["jobInfoModel"]
async def scrape_jobs(job_keys: List[str]):
"""scrape job details from job page for given job keys"""
urls = [f"https://www.indeed.com/m/basecamp/viewjob?viewtype=embedded&jk={job_key}" for job_key in job_keys]
to_scrape = [ScrapeConfig(url=url, asp=True) for url in urls]
scraped = []
async for result in scrapfly.concurrent_scrape(to_scrape):
scraped.append(parse_job_page(result.content))
return scraped
We should see the full job description printed out if we run this scraper.
With this last feature, our scraper is ready to go! However, if we run our scraper at scale we might get blocked and for that, let's take a look at how we can integrate ScrapFly to avoid being blocked.
Bypass Indeed Blocking with ScrapFly
Indeed.com is using anti-scraping protection to block web scraper traffic. To get around this, we can use ScrapFly web scraping API, which offers several powerful features:
Now, we can enable Anti Scraping Protection bypass via asp=True flag:
from scrapfly import ScrapflyClient, ScrapeConfig
client = ScrapflyClient(key="YOUR_API_KEY")
result = client.scrape(ScrapeConfig(
url="https://www.indeed.com/jobs?q=python&l=Texas",
asp=True,
# ^ enable Anti Scraping Protection
))
print(result.content) # print page HTML
We can convert the rest of our scraper to ScrapFly SDK and avoid all blocking:
Full Indeed Scraper Code
Let's put everything we've learned in this tutorial together into a single scraper:
import asyncio
import json
import re
from typing import List
from urllib.parse import urlencode
from scrapfly import ScrapeApiResponse, ScrapeConfig, ScrapflyClient
def parse_search_page(result):
data = re.findall(r'window.mosaic.providerData\["mosaic-provider-jobcards"\]=(\{.+?\});', result.content)
data = json.loads(data[0])
return {
"results": data["metaData"]["mosaicProviderJobCardsModel"]["results"],
"meta": data["metaData"]["mosaicProviderJobCardsModel"]["tierSummaries"],
}
async def scrape_search(client: ScrapflyClient, query: str, location: str):
def make_page_url(offset):
parameters = {"q": query, "l": location, "filter": 0, "start": offset}
return "https://www.indeed.com/jobs?" + urlencode(parameters)
print(f"scraping first page of search: {query=}, {location=}")
result_first_page = await client.async_scrape(
ScrapeConfig(
make_page_url(0),
country="US",
asp=True,
)
)
data_first_page = parse_search_page(result_first_page)
results = data_first_page["results"]
total_results = sum(category["jobCount"] for category in data_first_page["meta"])
# there's a page limit on indeed.com
if total_results > 1000:
total_results = 1000
print(f"scraping remaining {total_results - 10 / 10} pages")
other_pages = [
ScrapeConfig(url=make_page_url(offset), country="US", asp=True) for offset in range(10, total_results + 10, 10)
]
async for result in client.concurrent_scrape(other_pages):
try:
data = parse_search_page(result)
results.extend(data["results"])
except Exception as e:
print(e)
return results
def parse_job_page(result: ScrapeApiResponse):
"""parse job data from job listing page"""
data = re.findall(r"_initialData=(\{.+?\});", result.content)
data = json.loads(data[0])
return data["jobInfoWrapperModel"]["jobInfoModel"]
async def scrape_jobs(client: ScrapflyClient, job_keys: List[str]):
"""scrape job page"""
urls = [f"https://www.indeed.com/m/basecamp/viewjob?viewtype=embedded&jk={job_key}" for job_key in job_keys]
scraped = []
async for result in client.concurrent_scrape([ScrapeConfig(url=url, country="US", asp=True) for url in urls]):
scraped.append(parse_job_page(result))
return scraped
async def main():
with ScrapflyClient(key="YOUR SCRAPFLY KEY", max_concurrency=2) as client:
search_results = await scrape_search(client, "python", "Texas")
print(json.dumps(search_results, indent=2))
_found_job_ids = [result["jobkey"] for result in search_results]
job_results = await scrape_jobs(client, job_keys=_found_job_ids[:10])
print(json.dumps(job_results, indent=2))
asyncio.run(main())
By using scrapfly-sdk instead of httpx we can safely avoid scraper blocking with very few modifications to our code!
Indeed Scraping Summary
In this short web scraping tutorial, we've looked at web scraping Indeed.com job listing search. We built a search URL using custom search parameters and parsed job data from the embedded JSON data by using regular expressions. As a bonus, we also looked at scraping full job listing descriptions and how to avoid blocking using Scrapfly SDK.
Goat.com is a rising storefront for luxury fashion apparel items. It's known for high quality apparel data so in this tutorial we'll take a look how to scrape it using Python.
In this fashion scrapeguide we'll be taking a look at Fashionphile - another major 2nd hand luxury fashion marketplace. We'll be using Python and hidden web data scraping to grap all of this data in just few lines of code.