Screen scraping a site with Python and storing the results into a sqlite db

This is a small program. I was tasked with retrieving a small set of data from a webpage by screenscraping using python.

http://money.livemint.com/IID64/F132540/Financial/Ratios/Company.aspx

Eps
This is the data I should retrieve. I never learnt Python properly but I could do it. That is the beauty of Python. Python has an interface to sqlite - the smallest db engine - called "Pysqlite". The library to import is called "sqlite3"

dbconn = sqlite3.connect('db/tcs_eps.db')

dbc = dbconn.cursor()

dbc.execute("CREATE TABLE IF NOT EXISTS EPSTABLE(DATE TEXT,EPS TEXT)")

dbc.execute("DELETE FROM EPSTABLE")

 

 

This part of the code creates a connection to a database file. If the file doesn't exist, it will be created. But the directory path should exist otherwise it'll throw an error. Sqlite is a file based database system unlike the server-client based ones like mysql, db2 etc.. Then it'll create a table if it doesn't exist already (i.e. during first run). It'll truncate the data from the table otherwise next time, same set of data will repeat in my tables.

host = "money.livemint.com" 

epspage = "/IID64/F132540/Financial/Ratios/Company.aspx" 

print "Please wait.. It will take some time depending on your connection speed.."

con = httplib.HTTPConnection(host)

con.connect()

con.request("GET", epspage)

resp = con.getresponse()

data = resp.read()

 

This part of the code opens up a connection to the host and tries to GET the page and then it reads the "data" part of the response. (Response object has so many other stuffs like status, headers etc..)

This data is the code of our html page. Analysing the content, I figured out that I should remove the unnecessary data above and below our interested part. For that I need to find a unique string above and below our part so that I can index them and take the substring out. Those indices were "InnerTable" and "R5". They were unique and appear only once and above and below our part in the file.

 

start=string.index(data,"InnerTable")

stop=string.index(data,"R5")

data = data[start:stop]

There are some html entities in that page which I removed using 

data = re.sub(r'[&nbspamltg]*;','',data)

This is not necessary though but I did it for my sake.

 

months = ['Date']+re.findall(r'[a-zA-Z]{1,3}\d\d\d\d',data)

earnings = ['Earnings/share (Rs)']+re.findall(r'\d\d\.\d\d',data)

 

Using this regex, I find out the date pattern and earnings per share pattern and store them in two lists. (The regex in second line should be changed to match any number of digits. I'm such a poor regex coder.)

 

for month, earning in zip(months, earnings):

    dbc.execute('INSERT INTO EPSTABLE VALUES (?,?)' , (month,earning))

dbconn.commit()

for month,earning in dbc.execute('SELECT * FROM EPSTABLE'):

    print '%s\t\t\t\t\t%s' % (month, earning)

dbconn.close()

 

 

Traversing elements simultaneously through two lists, they are inserted into the table and committed. Then traversing through each row in table and printing them. This program is just for learning coding in python with sqlite.

Full Program:

import httplib,string,re,sqlite3

dbconn = sqlite3.connect('db/tcs_eps.db')

dbc = dbconn.cursor()

dbc.execute("CREATE TABLE IF NOT EXISTS EPSTABLE(DATE TEXT,EPS TEXT)")

dbc.execute("DELETE FROM EPSTABLE")

host = "money.livemint.com" 

epspage = "/IID64/F132540/Financial/Ratios/Company.aspx" 

print "Please wait.. It will take some time depending on your connection speed.."

con = httplib.HTTPConnection(host)

con.connect()

con.request("GET", epspage)

resp = con.getresponse()

data = resp.read()

print "=================================================="

start=string.index(data,"InnerTable")

stop=string.index(data,"R5")

data = data[start:stop]

data = re.sub(r'[&nbspamltg]*;','',data)

months = ['Date']+re.findall(r'[a-zA-Z]{1,3}\d\d\d\d',data)

earnings = ['Earnings/share (Rs)']+re.findall(r'\d\d\.\d\d',data)

for month, earning in zip(months, earnings):

    #print '%s\t\t\t\t\t%s' % (month, earning)

    dbc.execute('INSERT INTO EPSTABLE VALUES (?,?)' , (month,earning))

dbconn.commit()

 

for month,earning in dbc.execute('SELECT * FROM EPSTABLE'):

    print '%s\t\t\t\t\t%s' % (month, earning)

dbconn.close() 

Tcsscr

Posted via email from Art, Science & Technology

Bash script to find mutual friends in twitter

My manager gave me a simple(tough for me) assignment to learn..

Problem: Write a command line app using your favourite language that accepts 2 facebook ids and return a list of common friends between the 2 ids.

I couldn't! I could make a program that list my friends but not others because it's private information and it requires others to allow my application blah blah..

So I gave a try for twitter and I SUCCESSFULLY DID IT! ;) Because following and followers list are public in twitter.

Check out the script and screenshot

Script

#!/bin/bash

link1='https://api.twitter.com/1/friends/ids.json?screen_name='$1

link2='https://api.twitter.com/1/friends/ids.json?screen_name='$2

curl $link1 > .fol.tmp

curl $link2 > .fol2.tmp

cat .fol.tmp | sed 's/.*\[\([0-9,]*\)\].*/\1/' | sed 's/,/\n/g' | sort > .ids.tmp

cat .fol2.tmp | sed 's/.*\[\([0-9,]*\)\].*/\1/' | sed 's/,/\n/g' | sort > .ids2.tmp

#comm -12 .ids.tmp .ids2.tmp | tr '\n' ',' | sed 's/,$//' > .comids.tmp

#comm -12 is same as grep -xFf :)

grep -xFf .ids.tmp .ids2.tmp | tr '\n' ',' | sed 's/,$//' > .comids.tmp

comids=`cat .comids.tmp`

comidlink='https://api.twitter.com/1/users/lookup.json?user_id='$comids

curl $comidlink > .lookup.tmp

cat .lookup.tmp | tr ',' '\n' | grep '"name"' | sed 's/.*:\"\([^\"]*\)\"/\1/g'

rm .fol.tmp .fol2.tmp .ids.tmp .ids2.tmp .comids.tmp .lookup.tmp

Note: I'm an amateur programmer. This code may not be the most efficient but it does the job well.

Screenshot:

Mutualfriends2

Posted via email from Art, Science & Technology

Neembuu Uploader crossed 10k+ downloads and featured in a Japanese Magazine

Hi y'all,

I hadn't been updating on NU for a long time after getting job. Though I am sincerely committed to my employers, I will still be responsible to my previous projects that helped me improve in life. I will use my weekends on them. Shashaank (Neembuu Admin) has a lots of plans for Neembuu, Neembuu Uploader, JPFM, JD and Vuze all combined. Lots of works ahead ;-)

NU Stats:

Downloads: 10325 (at the time of writing this)
Top Country: France :)
You can always see the latest stats at http://neembuuuploader.sf.net/downloads.html

France overtook Russia as the top downloading country. Seems like we have a lot of fans there.

AND I am very happy now to announce that Neembuu Uploader has been featured in a Japanese Tech magazine called "iP!". A month ago I got this mail from them:

Dear Vigneshwaran Raveendran,

I am an editor of a Japanese magazine called "iP!", a magazine for
Windows users with original DVD-ROMs to offer data/software.
I would like to introduce your "Neembuu Uploader"to Japanese Windows users.
And I am glad that you would give me kind permission to put your soft
into our DVD-ROM.
If OK,I would like to introduce "Neembuu Uploader" continuously from now on.

Please let me  know when you have any questions or find any problems
for introducing your soft.
I'm looking forward to hearing from you soon.

Published information is the following.
Please correct it when the mistake is found.
<snipped> 

And I replied:

Dear Xxxxxxx Xxx,

I am really glad to know that my product "Neembuu Uploader" will be introduced in 
your magazine. You are ALLOWED to feature it in your magazine. Please make sure
that you include my name "Vigneshwaran Raveendran" and the homepage url 
http://neembuuuploader.sourceforge.net/ anywhere in the body of the content.

I have one request. I am living in India where I cannot get access to your "iP!" magazine.
So after the magazine is published, please send me a scanned image of the page where
"Neembuu Uploader" is featured.

Thank you

After a long time, yesterday they replied:

Vigneshwaran Raveendran様

お世話になっております。晋遊舎の静内です。
このたびはソフトウエアの掲載に
ご協力ありがとうございました。

無事に誌面が完成いたしましたのでお送りいたします。
引き続きまして、変わらぬご愛顧のほど、
どうぞよろしくお願い申し上げます。

(Translate if you don't know japanese)

They attached a pdf of the scanned magazine. I took this screenshot of the part where NU appears. Check it out:

28

Posted via email from Art, Science & Technology