Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Implement a Simple Web Crawler in Python

Implement a Simple Web Crawler in Python

Document Object Reference Manual Python3 Examples

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:

               

print

(

href

)

   

else

:

       

print

(

f

"Failed to retrieve the webpage. Status code: {response.status_code}"

)

Usage examples

simple_web_crawler

(

'https://www.example.com'

)

Code analysis:

  1. import requests: Import the requests library, used to send HTTP requests.
  2. from bs4 import BeautifulSoup: Import the BeautifulSoup class, used to parse HTML content.
  3. def simple_web_crawler(url):: Define a function simple_web_crawler, taking a URL as a parameter.
  4. response = requests.get(url): Send a GET request to the specified URL and store the response in response variable.
  5. if response.status_code == 200:: Check whether the request succeeded (status code 200 means success).
  6. soup = BeautifulSoup(response.text, 'html.parser'): When using BeautifulSoup Parse the HTML content.
  7. links = soup.find_all('a'): Find all the tags, which usually contain links.
  8. for link in links:: Iterate over all the links.
  9. href = link.get('href'): Extract each link's href attribute.
  10. if href:: Check whether href exists.
  11. print(href): Print the link.
  12. 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.

Document Object Reference Manual Python3 Examples