Implement a Simple Web Crawler in Python
We will use Python's requests library to send HTTP requests, and the BeautifulSoup library to parse HTML content. This simple web crawler will extract all links from a web page.
Example
import
requests
from
bs4
import
BeautifulSoup
def
simple_web_crawler
(
url
)
:
Send an HTTP request
response
=
requests.
get
(
url
)
Check whether the request succeeded
if
response.
status_code
==
200
:
Parse the HTML content
soup
=
BeautifulSoup
(
response.
text
,
'html.parser'
)
Find all the links
links
=
soup.
find_all
(
'a'
)
Extract and print the links
for
link
in
links:
href
=
link.
get
(
'href'
)
if
href:
(
href
)
else
:
(
f
"Failed to retrieve the webpage. Status code: {response.status_code}"
)
Usage examples
simple_web_crawler
(
'https://www.example.com'
)
Code analysis:
import requests: Import therequestslibrary, used to send HTTP requests.from bs4 import BeautifulSoup: Import theBeautifulSoupclass, used to parse HTML content.def simple_web_crawler(url):: Define a functionsimple_web_crawler, taking a URL as a parameter.response = requests.get(url): Send a GET request to the specified URL and store the response inresponsevariable.if response.status_code == 200:: Check whether the request succeeded (status code 200 means success).soup = BeautifulSoup(response.text, 'html.parser'): When usingBeautifulSoupParse the HTML content.links = soup.find_all('a'): Find all thetags, which usually contain links.for link in links:: Iterate over all the links.href = link.get('href'): Extract each link'shrefattribute.if href:: Check whetherhrefexists.print(href): Print the link.else:: If the request fails, print an error message.
Output: after running the code, the program prints out https://www.example.com all the links on the page. The exact output depends on the content of the target page. For example:
https://www.iana.org/domains/example
This is just an example; actual output may vary.
Python3 Examples