473,811 Members | 1,881 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

urllib - changing the user agent

I'm writing a function that will query the comp.lang.pytho n newsgroup
via google groups....... (I haven't got nntp access from work..)

I'm using urllib (for the first time)..... and google don't seem very
keen to let me search the group from within a program - the returned
pages all tell me 'you're not allowed to do that' :-)

I read in the urllib manual pages :

class URLopener( [proxies[, **x509]])

Base class for opening and reading URLs. Unless you need to support
opening objects using schemes other than http:, ftp:, gopher: or
file:, you probably want to use FancyURLopener.
By default, the URLopener class sends a User-Agent: header of
"urllib/VVV", where VVV is the urllib version number. Applications can
define their own User-Agent: header by subclassing URLopener or
FancyURLopener and setting the instance attribute version to an
appropriate string value before the open() method is called.
Could anyone tell me how to subclass this correctly with the version
attribute set and what text string I should use to mimic Internet
explorer and/or mozilla ?
Ta

Fuzzy
Jul 18 '05 #1
7 5828
mi*****@foord.n et (Fuzzyman) writes:
[...]
I'm using urllib (for the first time)..... and google don't seem very
keen to let me search the group from within a program - the returned
pages all tell me 'you're not allowed to do that' :-)
Don't do it, then. Use the google API (mind you, not certain that
google groups is part of that).

[...] Could anyone tell me how to subclass this correctly with the version
attribute set and what text string I should use to mimic Internet
explorer and/or mozilla ?


IIRC,

opener.addheade rs = [("User-agent", "whatever")]

Use a program like ethereal to find what your browser sends for
"whatever".
John
Jul 18 '05 #2
"Fuzzyman" <mi*****@foord. net> wrote in message
news:80******** *************** ***@posting.goo gle.com...
I'm writing a function that will query the comp.lang.pytho n newsgroup
via google groups....... (I haven't got nntp access from work..)

I'm using urllib (for the first time)..... and google don't seem very
keen to let me search the group from within a program - the returned
pages all tell me 'you're not allowed to do that' :-)

I read in the urllib manual pages :

class URLopener( [proxies[, **x509]])

Base class for opening and reading URLs. Unless you need to support
opening objects using schemes other than http:, ftp:, gopher: or
file:, you probably want to use FancyURLopener.
By default, the URLopener class sends a User-Agent: header of
"urllib/VVV", where VVV is the urllib version number. Applications can
define their own User-Agent: header by subclassing URLopener or
FancyURLopener and setting the instance attribute version to an
appropriate string value before the open() method is called.
Could anyone tell me how to subclass this correctly with the version
attribute set and what text string I should use to mimic Internet
explorer and/or mozilla ?
Ta

Fuzzy


I normally use something like this for crawling webpages.

import urllib
urllib.URLopene r.version = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT
5.0; T312461)'
urllib.FancyURL opener.prompt_u ser_passwd = lambda self, host, realm: (None,
None)

Anthony McDonald
Jul 18 '05 #3
On 9 Jan 2004 05:09:41 -0800, mi*****@foord.n et (Fuzzyman) wrote:

[ wants to change the user-agent in HTTP request from urllib ]

Fuzzy --

I take the easy way out, and use urllib2, instead:

url = "http//www.spam.com/eggs.html"
req_headers = {
'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
}
req = urllib2.Request (url, None, req_headers)
Jul 18 '05 #4
On 09 Jan 2004 14:12:56 +0000, jj*@pobox.com (John J. Lee) wrote:
Don't do it, then. Use the google API (mind you, not certain that
google groups is part of that).


Can Google APIs be used to access Google Groups? ...

No. The Google Web APIs service can only be used to search
Google's main index of 3 billion web pages.

http://www.google.com/apis/api_faq.html#ini2

Jul 18 '05 #5
Terry Carroll <ca*****@tjc.co m> writes:
On 9 Jan 2004 05:09:41 -0800, mi*****@foord.n et (Fuzzyman) wrote:

[ wants to change the user-agent in HTTP request from urllib ]

Fuzzy --

I take the easy way out, and use urllib2, instead: [...] req = urllib2.Request (url, None, req_headers)


or again, you can set .addheaders on OpenerDirector (which will cause
those headers to be added to all requests).
John
Jul 18 '05 #6
|Thus Spake John J. Lee On the now historical date of Fri, 09 Jan 2004
20:16:54 +0000|
or again, you can set .addheaders on OpenerDirector (which will cause
those headers to be added to all requests).


This, however, does not stop the original User-agent header to be sent,
and google still filters out the request. Instead, it just causes a
second user-agent to be sent.

Here is the very bad code I used to solve this problem. There are better
ways, I assure you, but it should point you in the right direction. You
should probably do this with inheritance, but for my quick script, this is
what I did.

----
#Override the default OpenerDirector Class Init.
#OpenerDirector *insists* on adding a User-Agent
#That some websites don't like.
foo = OpenerDirector. __init__
def bar(self, Agent='None'):
foo(self)
self.addheaders = [('User-Agent',Agent)]

OpenerDirector. __init__ = bar
-----

HTH

Sam Walters.

--
Never forget the halloween documents.
http://www.opensource.org/halloween/
""" Where will Microsoft try to drag you today?
Do you really want to go there?"""

Jul 18 '05 #7
Samuel Walters <sw************ *@yahoo.com> writes:
|Thus Spake John J. Lee On the now historical date of Fri, 09 Jan 2004
20:16:54 +0000|
or again, you can set .addheaders on OpenerDirector (which will cause
those headers to be added to all requests).

(just to clarify, I meant an OpenerDirector instance, not the class
itself)

This, however, does not stop the original User-agent header to be sent,
and google still filters out the request. Instead, it just causes a
second user-agent to be sent.
No, it does stop them being sent. Perhaps you mutated the base class
..addheaders by mistake (using .append(("User-agent", "blah")), for
example)? Don't do that! Mutating class attributes is a bad idea.

Here is the very bad code I used to solve this problem. There are better
ways, I assure you, but it should point you in the right direction. You

[...]

No need to assure me of *that* <wink>. You can call a base class
constructor directly, you know. And clobbering the base class'
constructor is another very bad idea.
John
Jul 18 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
4478
by: Michael | last post by:
How do you change the user agent reported by urllib? I need to access a resource that rejects anything but IE.
11
5062
by: Pater Maximus | last post by:
I am trying to implement the recipe listed at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/211886 However, I can not get to first base. When I try to run import urllib fo=urllib.urlopen("http://www.dictionary.com/") page = fo.read() I get:
0
1693
by: Chris | last post by:
hello, I have an odd behaviour. I try to download some files connected to a specific webpage (e.g. all stylesheets) with urllib2.urlopen(x) This seems to hang on the 2nd file or so. Doing the exact same thing via urllib.urlopen(x) does work without a hitch...
8
3507
by: Gabriel Zachmann | last post by:
Here is a very simple Python script utilizing urllib: import urllib url = "http://commons.wikimedia.org/wiki/Commons:Featured_pictures/chronological" print url print file = urllib.urlopen( url ) mime = file.info() print mime
1
496
by: evanpmeth | last post by:
I have tried multiple ways of posting information to a website and have failed. I have seen this problem on other forums can someone explain or point me to information on how POST works through urllib an different broweser (what is the difference). my first attempt was out of the docs: Code: import httplib, urllib params = urllib.urlencode({'email' : 'a@a.com',
4
1677
by: junkdump2861 | last post by:
Here's the problem: using Netscape 7.1, I type use the view page source command (url is http://en.wikipedia.org/wiki/Cain) and save the raw HTML file and it's 67 kb, and has the addresses of all the images in it. I want the exact same thing from my Python script, but I'm not getting it. Instead, I get a file only 21 kb that has no image addresses. Here's the code I use: import urllib f =...
5
1752
by: Adrian Smith | last post by:
I'm trying to use urllib2 to download a page (I'd rather use urllib, but I need to change the User-Agent header to look like a browser or G**gle won't send it to me, the big meanies). The following (pinched from Dive Into Python) seems to work perfectly in Idle, but falls at the final hurdle when run as a cgi script - can anyone suggest anything I may have overlooked? request = urllib2.Request(some_URL) request.add_header('User-Agent',...
0
3703
by: johnpollard | last post by:
For some reason this script isn't working and I dont know what it is. I believe the problem lies in the following lines of code since the script works with a different website and username/password combination: resp = opener.open('http://www.amm.com/login.asp') theurl = 'http://www.amm.com/login.asp' body={'username':'AMMT54590570','password':'AMMT32 564288'} #!/usr/bin/env python # -*- coding: UTF-8 -*-
5
2603
by: Thierry | last post by:
Hello fellow pythonists, I'm a relatively new python developer, and I try to adjust my understanding about "how things works" to python, but I have hit a block, that I cannot understand. I needed to output unicode datas back from a web service, and could not get back unicode/multibyte text before applying an hack that I don't understand (thank you google) I have realized an wxPython simple application, that takes the input
0
9605
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10389
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10402
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10135
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7670
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6890
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5554
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5692
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4339
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.