Automation in Python: mass checking links for accessibility. Python that checks a list of URLs for accessibility (response code 200 or not)

Tr0jan_Horse

Moderator
Staff member
MODERATOR
ULTIMATE
PREMIUM
MEMBER
Joined
Oct 23, 2024
Messages
304
Reaction score
8,788
Deposit
0$
Automation in Python: Mass Checking Links for Accessibility

In the world of cybersecurity and web development, ensuring that your links are accessible is crucial. A simple way to automate this process is by using Python. In this article, we will explore how to create a script that checks a list of URLs for accessibility, specifically looking for a response code of 200.

Why Check URL Accessibility?

Checking the accessibility of URLs is essential for maintaining a healthy website. Broken links can lead to poor user experience and can negatively impact your site's SEO. Automating this process saves time and ensures that you can quickly identify and fix any issues.

Requirements

To get started, you will need:
- Python installed on your machine.
- The `requests` library, which can be installed via pip:

```
pip install requests
```

The Script

Below is a simple Python script that checks a list of URLs and reports their accessibility status:

[expand]
```python
import requests

def check_urls(urls):
for url in urls:
try:
response = requests.get(url)
if response.status_code == 200:
print(f"Accessible: {url}")
else:
print(f"Not Accessible (Status Code: {response.status_code}): {url}")
except requests.exceptions.RequestException as e:
print(f"Error: {url} - {e}")

if __name__ == "__main__":
url_list = [
"https://www.example.com",
"https://www.nonexistentwebsite.com",
"https://www.google.com"
]
check_urls(url_list)
```
[/expand]

How It Works

1. **Importing Libraries**: The script starts by importing the `requests` library, which is essential for making HTTP requests.
2. **Defining the Function**: The `check_urls` function takes a list of URLs and iterates through them.
3. **Making Requests**: For each URL, it attempts to make a GET request. If the response code is 200, it prints that the URL is accessible. If not, it prints the status code.
4. **Error Handling**: The script also handles exceptions, printing an error message if a request fails.

Running the Script

To run the script, simply save it as `check_links.py` and execute it in your terminal:

```
python check_links.py
```

You will see output indicating which URLs are accessible and which are not.

Conclusion

Automating the process of checking URL accessibility with Python is a straightforward yet powerful tool for web developers and cybersecurity professionals. By implementing this script, you can ensure that your links are functioning correctly, enhancing user experience and maintaining your site's integrity.

Feel free to modify the script to suit your needs, such as reading URLs from a file or adding more detailed logging. Happy coding!
 
Top Bottom