1

So my idea was to basically make something simple when a page re-directs it should just quit the script. Meaning:

Legit page: https://www.stackoverflow.com Redirected: https://www.stackoverflow.com/Helloworld

Right now I am just using

import requests

try:
    r = requests.get('https://www.stackoverflow.com')
    print r.status_code

except:
    sys.exit()

what I want to do is that whenever it the requests.get gets re-directed. It should hit the exception where I later can use sys.exit() Or it should just sys.exit() overall if it redirects.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Hellosiroverthere
  • 285
  • 10
  • 19
  • Could you disable redirect following and check whether the first status code is 3xx? – jonrsharpe Dec 07 '18 at 16:37
  • 1
    Possible duplicate of [Is there an easy way to request a URL in python and NOT follow redirects?](https://stackoverflow.com/questions/110498/is-there-an-easy-way-to-request-a-url-in-python-and-not-follow-redirects) – Daniel Pryden Dec 07 '18 at 16:38

1 Answers1

0

All redirects will have a status code like 3xx (which you can see in the HTTP standard). You can check the status code and use a regex to match it to that pattern. If it matches that pattern, then exit.

import re
import sys
import requests

r = requests.get('https://www.stackoverflow.com')
if re.search(r'^3', str(r.status_code)):
    sys.exit()

[EDIT]: Left out the str around r.status_code because it's an integer.

skyxie
  • 111
  • 7