473,725 Members | 1,980 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Retrieve HTML from site using cookies

Greetings gents. I'm a Railser working on a django app that needs to do
some scraping to gather its data.

I need to programatically access a site that requires a username and
password. Once I post to the login.php page, there seems to be a
redirect and it seems that the site is using a session (perhaps a
cookie) to determine whether the user is logged in. So I need to log in
and then have cookies and or sessions maintained as I access the page
that contains the content that I am actually interested in.

What is the simplest way to post data to a form, accept a cookie to
maintain the session (and support redirects) and then (now logged into
the site) retrieve the content of a page on the site?

Is their a library or technique that makes this simple?

Thanks!

Sep 21 '06 #1
1 2590
on************* @gmail.com wrote:
Greetings gents. I'm a Railser working on a django app that needs to do
some scraping to gather its data.

I need to programatically access a site that requires a username and
password. Once I post to the login.php page, there seems to be a
redirect and it seems that the site is using a session (perhaps a
cookie) to determine whether the user is logged in. So I need to log in
and then have cookies and or sessions maintained as I access the page
that contains the content that I am actually interested in.

What is the simplest way to post data to a form, accept a cookie to
maintain the session (and support redirects) and then (now logged into
the site) retrieve the content of a page on the site?

Is their a library or technique that makes this simple?

Thanks!
I submit to you, in its entirety a, a script I wrote to do this. I think
its simple enough to figure out the important parts. I left some
debugging code in. Sorry for no explanation, etc., but I'm still playing
with the new 2.5 distro! This program worked for me, but there may be
comment on whether its good code from others. Names have been changed to
protect the innocent.
James

#! /usr/bin/env python

import sys
import os.path
import time
import random
import urllib
import urllib2
import cookielib

class DummyError(Exce ption): pass
############### ############### ############### ############### ###########
# some constants
############### ############### ############### ############### ###########
COOKIEFILE = 'cookies.lwp'

pda = "http://www.somemapcomp any.com/"

signin_params = urllib.urlencod e({'email_addre ss':'y***@email .address',
'password':'you rpasshere',
'action':'log_i n',
'Submit':'Sign In'})

signout_params = urllib.urlencod e({'action':'si gn_out'})

download_dict = {'screen':'map_ details', 'action':'downl oad'}

info_dict = {'screen':'map_ details',
'back':'find_ma ps',
'view':'state'}

############### ############### ############### ############### ###########
# setup for cookies
############### ############### ############### ############### ###########
cj = cookielib.LWPCo okieJar()

if os.path.isfile( COOKIEFILE):
cj.load(COOKIEF ILE)

opener = urllib2.build_o pener(urllib2.H TTPCookieProces sor(cj))
urllib2.install _opener(opener)
############### ############### ############### ############### ###########
# make the signin request
############### ############### ############### ############### ###########
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
txheaders = {'User-agent' : user_agent}
req = urllib2.Request (pda, signin_params, txheaders)

############### ############### ############### ############### ###########
# download_map
############### ############### ############### ############### ###########
def download_map(ma p_id, urlopen=urllib2 .urlopen):

############### ############### ############### ############### #########
# download the map
############### ############### ############### ############### #########
download_dict['map_id'] = map_id
download_params = urllib.urlencod e(download_dict )

mapin = urlopen(pda + ("?%s" % download_params ))

mapout = open('map-%s' % map_id, "wb")
mapout.write(ma pin.read())
mapout.close()

############### ############### ############### ############### #########
# download the map info
############### ############### ############### ############### #########
info_dict['map_id'] = map_id
info_params = urllib.urlencod e(info_dict)

infoin = urlopen(pda + ("?%s" % info_params))

infoout = open('info-%s' % map_id, "wb")
infoout.write(i nfoin.read())
infoout.close()
############### ############### ############### ############### ###########
# signin and print info
############### ############### ############### ############### ###########
try:
signin = urllib2.urlopen (req)
except IOError, e:
print 'We failed to open "%s".' % pda
if hasattr(e, 'code'):
print 'We failed with error code - %s.' % e.code
else:
print
print 'Here are the headers of the page :'
print signin.info()
afile = open("signin.ht ml", "w")
afile.write(sig nin.read())
afile.close()
############### ############### ############### ############### ###########
# report and save cookies
############### ############### ############### ############### ###########
print
for index, cookie in enumerate(cj):
print index, ' : ', cookie

cj.save(COOKIEF ILE, True, True)

print
print "cookies=== >"
os.system('cat %s' % COOKIEFILE)
print "<===cookie s"

for map_id in xrange(1001, 1507):
try:
download_map(ma p_id)
wait = 7.5 + random.randint( 0,5)
print "=====waiti ng %s seconds..." % wait
time.sleep(wait )
except urllib2.HTTPErr or, e:
# except DummyError, e:
print "%s: failed to download" % map_id
print " HTTP ERROR:", e
else:
print "# Downloaded map %s successfully." % map_id

signout = urllib.urlopen( pda + ("?%s" % signout_params) )

afile = open("signout.h tml", "w")
afile.write(sig nout.read())
afile.close()
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
Sep 21 '06 #2

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

Similar topics

5
11200
by: David Rasmussen | last post by:
Some sites seem to be session driven in the sense that if I visit the homepage and do a few clicks I can navigate anywhere I want, but if I paste the current location into a new browser window after having navigated to some page, it doesn't work. It just returns to the start page or says "timeout" etc. This means that I can't read these pages from PHP with $string = file_get_contents('http://some.url/blah/deep/link');
7
29877
by: Eric | last post by:
I am certain the answer will be 'NO', but I wanted to ask anyway just incase I have missed something. Everyone knows that one pass data to a page in an anchor tag by using the GET Method: <a href="http://www.aaa.com/randompage.php?name=data"> What I am wondering is if there was a way to do the same thing, but use the POST Method instead...?
2
2084
by: Jim | last post by:
Hi, I'm working on an intranet site for a large client who has a search routine that runs on another intranet site on a different server. This search routine saves its searches in cookies for re-use. My client would like to display those saved searches on their own page. Is there any way that I can retrieve cookies from another site? I think this is impossible and I'll have to use an IFRAME with content from the other site, but I'd...
3
2636
by: Chuck Renner | last post by:
Please help! This MIGHT even be a bug in PHP! I'll provide version numbers and site specific information (browser, OS, and kernel versions) if others cannot reproduce this problem. I'm running into some PHP behavior that I do not understand in PHP 5.1.2. I need to parse the HTML from the following carefully constructed URI:
2
1775
by: * Tong * | last post by:
Hi, I'm wondering if you can show me an example php page that allows me to retrieve and display 3rd party pages. I.e., when my php script is called as http://site/path/getit.php?file_key it can retrieve from http://3rd.party/path2/name-with-file_key.htm and display the result back to the browser. I don't know php, and start to learning it. So I hope you can give me a full
4
1597
by: Jeff | last post by:
hey ASP.NET 2.0 I'm preparing for a certification exam on asp.net 2.0 and yesterday I took a skill assessment test on microsoft.com. One of the questions was about creating cookies. This was the question: "Which object or objects will you use to create and retrieve cookies"... 6 alternative answer were listed, below I show only 2 most relevant alternatives
1
1435
by: GpOscar | last post by:
Hey whats up.. i have created a form which does calculations i have installed it on the server and run on it all the other workstations. Now on this form there are some rates that change according to calculations. how can i retrieve the cookies from the server rather than stored on each individual workstation.? so that all the workstations have the same new rates.
0
1808
by: apondu | last post by:
I'm trying to screen scrape a site that requires a password. I am using C#.Net, i am new to this and with the information available around on the internet i just put tht information into the code. But still i am not able to achieve what i want to. I have posted the code which i have written, along with the site and the userid ans password
1
1348
by: snitu | last post by:
Hello I have a problem with how to use alternate stylesheet in my site home page using cookies. Normal html file is working with out using cookies.But i have to give authority to customer to use their own stylesheet for showing the home page of my site . If any one done this plz...................... Reply me. Thanks.
0
8888
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
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
9401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9257
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
9174
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
8096
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6011
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
4782
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2634
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.