The project outline:
Write a program that, given the URL of a web page, will attempt to download every linked page on the page. The program should flag any pages that have a 404 “Not Found” status code and print them out as broken links.
My solution:
# Usage: python link_verification.py "webpage to search"
import sys, requests, bs4
def link_validator(links):
for link in links:
page = link.get("href")
if str(page).startswith("https://"):
url = link.get("href")
res = requests.get(url)
try:
res.raise_for_status()
print(f"Page found: {page}")
except Exception as exc:
print(f"There was a problem with {page}:\n{exc}")
def main():
while True:
url = sys.argv[1] # Enter a website to search
res = requests.get(url)
try:
res.raise_for_status()
except Exception as exc:
print(f"There was a problem: {exc}")
continue
soup = bs4.BeautifulSoup(res.text, "html.parser")
links = soup.select("a")
link_validator(links)
print("Search complete")
break
if __name__ == '__main__':
main()