5

Is there anyway to open a URL in Python without opening a tab in a browser?

I have a preconstructed URL which I would like to run when the computer is idle e.g. http://foo.com/bar

I've been able to use the start and webbrowser methods but these open a new tab in my browser.

F.Y.I. The URL returns a blank page with nothing more than the word OK which I don't need.

Could anyone suggest any other way like via a batch or any other program that could do this?

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
Ari
  • 745
  • 1
  • 7
  • 23

3 Answers3

10

Use urllib (Python 2.x):

import urllib
urllib.urlopen('http://foo.com/bar')

(Python 3.x)

import urllib.request
urllib.request.urlopen('http://foo.com/bar')
Community
  • 1
  • 1
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • @sudo_O, Sorry, I don't understand what do you mean. Do you mean I should recommend to use urllib2 rather than urllib? – falsetru Jul 12 '13 at 13:35
  • Yes but as in @SamStudio8 request is an even better choice. Related quesiton http://stackoverflow.com/questions/2018026/should-i-use-urllib-or-urllib2-or-requests – Chris Seymour Jul 12 '13 at 13:39
5

You could also check out the requests module. If you don't need the actual content you could just check the HTTP status code?

import requests
result = requests.get('http://foo.com/bar')

if(result.status_code == 200): print("OK")
Sam Nicholls
  • 861
  • 4
  • 16
  • 1
    I'd agree with using requests over urllib(2); it's billed as 'http for humans' and generally follows a philosophy of being easy to use and read. – Will Jul 12 '13 at 13:08
  • 1
    I should have mentioned you'd need to install it first, you can run `pip install requests` on your terminal or alternatively follow the instructions [on the website](http://docs.python-requests.org/en/latest/user/install.html#get-the-code) to install it from the source. – Sam Nicholls Jul 12 '13 at 13:10
0

First Install "requests"

Run in command prompt :

pip install requests

then run this code :

username ='abcd'
password='password'
url = 'www.example.com/data/con'
r=requests.get(url)
page=r.content
print(page)