MyInternships.in

Python for Data & Web

Python Web Scraping with BeautifulSoup

Web scraping means pulling data out of a webpage's HTML automatically. In Python, that usually means pairing the requests library to fetch the page with BeautifulSoup to read and search through it.


Installing the Tools

You need two packages: requests to download the page, and beautifulsoup4 (imported as bs4) to parse and search its HTML.

Install requests and BeautifulSoup
Terminal
pip install requests beautifulsoup4

Fetching and Parsing a Page

First fetch the raw HTML with requests, then hand its text to BeautifulSoup, which turns it into a searchable tree of tags you can navigate like a document.

Loading a page into BeautifulSoup
Python
import requests
from bs4 import BeautifulSoup

response = requests.get("https://example.com")
soup = BeautifulSoup(response.text, "html.parser")

print(soup.title.text)

find() and find_all()

find() returns the first matching tag on the page, while find_all() returns a list of every match, which you can then loop over like any other list.

Finding elements by tag and class
Python
import requests
from bs4 import BeautifulSoup

response = requests.get("https://example.com/jobs")
soup = BeautifulSoup(response.text, "html.parser")

first_heading = soup.find("h2")
print(first_heading.text)

job_titles = soup.find_all("h2", class_="job-title")
for job in job_titles:
    print(job.text.strip())

Using select() with CSS Selectors

If you already know CSS selectors, select() lets you find elements the same way, which is often shorter than chaining find calls together.

Selecting with CSS-style selectors
Python
links = soup.select("div.job-card a")
for link in links:
    print(link.text.strip(), link.get("href"))

Notice that .text (or .get_text()) pulls out the readable text inside a tag, while .get("href") reads an attribute such as a link URL — these two patterns cover most scraping needs.

⚠️

Always check a site's robots.txt file and terms of service before scraping it, avoid hammering a server with rapid requests, and never scrape content you plan to republish without permission.

💡

Wrap requests and parsing in a try/except block using exceptions, since real websites change their HTML structure often and can break your selectors.

Related Python Topics

Keep learning with these closely related lessons.

Ready to use your Python skills?

Find Python, data science and software internships and fresher jobs across India.

Browse Python Internships