Subversion Repositories SmartDukaan

Rev

Rev 1943 | Rev 1963 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1942 vikas 1
#!/usr/bin/python
2
 
3
"""
4
 
5
 This script prints date of run, search-string, and position and page number where saholic result 
6
 first appears in google search results.
7
 
8
"""
9
 
10
import sys, pycurl, re
11
import datetime, time
12
import random
13
import MySQLdb
14
 
15
 
16
 
17
# some initial setup:
18
USER_AGENT = 'Mozilla/4.0 (compatible; MSIE 6.0)'
19
# USER_AGENT = 'Mozilla/5.0'
20
FIND_DOMAIN = 'www.saholic.com'
21
LOCALE = '.co.in'
22
MAX_PAGE = 10
23
NUM_PER_PAGE = 100
1958 vikas 24
SEARCH_STRING_MAX_SLEEP = 60 #seconds
1942 vikas 25
PAGE_MAX_SLEEP = 10 #seconds
26
DB_HOST = "localhost"
27
DB_USER = "root"
28
DB_PASSWORD = "shop2020"
29
DB_NAME = "serp"
30
 
31
# define class to store result:
32
class ResposeStorage:
33
  def __init__(self):
34
    self.contents = ''
35
 
36
  def body_callback(self, buf):
37
    self.contents = self.contents + buf
38
 
39
class RankCheck:
40
  def __init__(self, searchStrinfMaxSleep=SEARCH_STRING_MAX_SLEEP, pageSleep=PAGE_MAX_SLEEP):
41
    self.searchStrinfMaxSleep = searchStrinfMaxSleep
42
    self.pageSleep = pageSleep
43
    self.userAgent = USER_AGENT
44
    self.findDomain = FIND_DOMAIN
45
    self.locale = LOCALE
46
    self.maxPage = MAX_PAGE
47
    self.numPerPage = NUM_PER_PAGE
48
    self.searchStrings = []
49
    self.results = []
50
    self.db_mode = False
51
    self.breakAfterNextItr = False
52
 
53
  def addSearchStrings(self, searchStrings):
54
    self.searchStrings.extend(searchStrings)  
55
 
56
  def init_curl(self):
57
    # set up curl:
58
    rankRequest = pycurl.Curl()
59
    rankRequest.setopt(pycurl.USERAGENT, USER_AGENT)
60
    rankRequest.setopt(pycurl.FOLLOWLOCATION, 1)
61
    rankRequest.setopt(pycurl.AUTOREFERER, 1)
62
    rankRequest.setopt(pycurl.COOKIEFILE, '')
63
    rankRequest.setopt(pycurl.HTTPGET, 1)
64
    rankRequest.setopt(pycurl.REFERER, '')
65
    return rankRequest
66
 
67
  def start(self):
68
    i = 0
69
    for search_string in self.searchStrings:
70
      i += 1
71
      if i%30 == 0:
1958 vikas 72
        time.sleep(random.randint(60*5, 60*15)) # sleep for 2 to 10 min after 20 queries
1942 vikas 73
      self.find_google_position(search_string)
74
      if self.db_mode:
75
        time.sleep(random.randint(0, self.searchStrinfMaxSleep))
76
 
77
      if(len(self.results) >= 100 and self.db_mode):
78
        self.pushResultsToDb()
79
 
80
      if self.breakAfterNextItr:
81
        break
82
 
83
    if(len(self.results) > 0 and self.db_mode):
84
      self.pushResultsToDb()
85
 
86
  def search_page(self, page, page_url):
87
    # instantiate curl and result objects:
88
    rankCheck = ResposeStorage();
89
    rankRequest = self.init_curl()
90
    rankRequest.setopt(pycurl.WRITEFUNCTION, rankCheck.body_callback)
91
    rankRequest.setopt(pycurl.URL, page_url + '&start=' + str(page * NUM_PER_PAGE))
92
    rankRequest.perform()
93
    # close curl:
94
    rankRequest.close()
95
 
96
    # collect the search results
97
    html = rankCheck.contents
98
    counter = page * NUM_PER_PAGE
99
    result = 0
100
 
101
    if html.count("Our systems have detected unusual traffic from your computer network.") > 0:
102
      print "Blocked by Google"
103
      self.breakAfterNextItr = True
104
      return -1
105
    url = unicode(r'(<h3 class="r"><a href=")((https?):((//))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)')
106
    for google_result in re.finditer(url, html):
107
      # print m.group()
108
      this_url = google_result.group()
109
      this_url = this_url[23:]
110
      counter += 1
111
 
112
      google_url_regex = re.compile("((https?):((//))+([\w\d:#@%/;$()~_?\+-=\\\.&])*" + FIND_DOMAIN + "+([\w\d:#@%/;$()~_?\+-=\\\.&])*)")
113
      google_url_regex_result = google_url_regex.match(this_url)
114
      if google_url_regex_result:
115
        result = counter
116
        break
117
 
118
    return result
119
 
120
  def find_google_position(self, search_string):
121
    ENGINE_URL = 'http://www.google' + LOCALE + '/search?q=' + search_string.replace(' ', '+') + '&num=' + str(NUM_PER_PAGE)
122
    # print ENGINE_URL
123
 
124
    # run curl:
125
    for i in range(0, MAX_PAGE):
126
      position = self.search_page(i, ENGINE_URL)
127
      time.sleep(random.randint(0, self.pageSleep))
128
 
129
      if position != 0:
130
        break
131
 
132
    if position ==-1:
133
      return
134
    if position == 0:
135
      position = NUM_PER_PAGE * MAX_PAGE
136
 
137
    self.results.append((position, ((position-1)/10 + 1), search_string))
138
    print "{0:s}, {1:s}, {2:d}, {3:d}".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), search_string, position, (position-1)/10 + 1)
139
 
140
  def getDbConnection(self):
141
    return MySQLdb.connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
142
 
143
  def closeConnection(self, conn):
144
    conn.close()
145
 
146
  def loadSearchStringsFromDb(self):
147
    conn = self.getDbConnection()
148
 
149
    # Prepare SQL query to INSERT a record into the database.
150
    sql = "SELECT query FROM query where is_active = 1"
151
    try:
152
      # prepare a cursor object using cursor() method
153
      cursor = conn.cursor()
154
      # Execute the SQL command
155
      cursor.execute(sql)
156
      # Fetch all the rows in a list of lists.
157
      results = cursor.fetchall()
158
      for row in results:
159
        self.searchStrings.append(row[0])
160
      cursor.close()
161
    except Exception as e:
162
      print "Error: unable to fetch data"
163
      print e
164
 
165
    self.closeConnection(conn)
166
 
167
  def pushResultsToDb(self):
168
    conn = self.getDbConnection()
169
 
170
    try:
171
      # prepare a cursor object using cursor() method
172
      cursor = conn.cursor()
173
 
174
      cursor.executemany (
175
          """
176
              insert into rank(query_id, date, position, page) 
177
              select id , now(), %s, %s from query where query = %s;
178
          """, self.results)
179
      conn.commit()
180
      self.results = []
181
      cursor.close()
182
    except Exception as e:
183
      print "Error: unable to insert row"
184
      print e
185
 
186
    self.closeConnection(conn)
187
 
188
 
189
 
190
def main():
191
  if len(sys.argv) > 1:
192
    rank_cheker = RankCheck(0, 0)
193
    rank_cheker.addSearchStrings(sys.argv[1:])
194
  else:
195
    rank_cheker = RankCheck()
196
    rank_cheker.loadSearchStringsFromDb()
197
    rank_cheker.db_mode = True
198
 
199
  rank_cheker.start()
200
 
201
if __name__ == '__main__':
202
    main()