Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

python - Returning a list of output using URLLIB

I have been using the below to checking if a website is valid or not -

  from urllib.request import Request, urlopen
  from urllib.error import URLError, HTTPError
  req = Request("http://www.google.com/")
     try:
      response = urlopen(req)
    except HTTPError as e:
      print('The server couldn't fulfill the request.')
      print('Error code: ', e.code)
    except URLError as e:
      print('We failed to reach a server.')
      print('Reason: ', e.reason)
    else:
      print ('Website is working fine')

However, I need to input multiple websites at once (list created for the same) and get output like below-

www.google.com - Website is working fine
www.Facebook.com - Website is working fine
www.themoneytizer.net - We failed to reach a server.Reason:  [Errno 11001] getaddrinfo failed.

Kindly help with the code

question from:https://stackoverflow.com/questions/66052419/returning-a-list-of-output-using-urllib

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Please try like below. Hopefully you will get some idea.

from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
list_of_website = ['http://www.google.com/','https://paste.ubuntu.com/','http://algotoolz.com/']

for website in list_of_website:
  req = Request(website)
  try:
      response = urlopen(req)
  except HTTPError as e:
      print('The server couldn't fulfill the request.')
      print('Error code: ', e.code)
  except URLError as e:
      print('We failed to reach a server.')
      print('Reason: ', e.reason)
  else:
      print ('Website is working fine')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...