2

I have this code and I was wondering if there was any way to add a timeout delay:

req = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) WD = urlopen(req).read() 

1 Answer 1

5

The urlopen() function has a timeout method inbuilt:

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). This actually only works for HTTP, HTTPS and FTP connections.

So in your code:

time = 50 WD = urlopen(req, timeout=time).read() 

You can only change the request your side (i.e. client side), with the argument above. Server side may also send a timeout, but there is nothing that can be done to change that.

Sign up to request clarification or add additional context in comments.

3 Comments

I see. For some reason when I put "timeout=5" for example in the 'req' variable it gave me an error.
@ProgrammerNZ There are a number of possiblities. If you post the exact error I/someone else will do my/their best to try and figure it out
As a test I ran this: from urllib.request import *; response = urlopen(Request('https://www.python.org'), timeout=50) that worked fine for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.