Subversion Repositories SmartDukaan

Rev

Rev 1943 | Go to most recent revision | Details | 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
24
SEARCH_STRING_MAX_SLEEP = 30 #seconds
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
      print i
72
      if i%30 == 0:
73
        time.sleep(random.randint(60*2, 60*10)) # sleep for 2 to 10 min after 20 queries
74
      self.find_google_position(search_string)
75
      if self.db_mode:
76
        time.sleep(random.randint(0, self.searchStrinfMaxSleep))
77
 
78
      if(len(self.results) >= 100 and self.db_mode):
79
        self.pushResultsToDb()
80
 
81
      if self.breakAfterNextItr:
82
        break
83
 
84
    if(len(self.results) > 0 and self.db_mode):
85
      self.pushResultsToDb()
86
 
87
  def search_page(self, page, page_url):
88
    # instantiate curl and result objects:
89
    rankCheck = ResposeStorage();
90
    rankRequest = self.init_curl()
91
    rankRequest.setopt(pycurl.WRITEFUNCTION, rankCheck.body_callback)
92
    rankRequest.setopt(pycurl.URL, page_url + '&start=' + str(page * NUM_PER_PAGE))
93
    rankRequest.perform()
94
    # close curl:
95
    rankRequest.close()
96
 
97
    # collect the search results
98
    html = rankCheck.contents
99
    counter = page * NUM_PER_PAGE
100
    result = 0
101
 
102
    if html.count("Our systems have detected unusual traffic from your computer network.") > 0:
103
      print "Blocked by Google"
104
      self.breakAfterNextItr = True
105
      return -1
106
    url = unicode(r'(<h3 class="r"><a href=")((https?):((//))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)')
107
    for google_result in re.finditer(url, html):
108
      # print m.group()
109
      this_url = google_result.group()
110
      this_url = this_url[23:]
111
      counter += 1
112
 
113
      google_url_regex = re.compile("((https?):((//))+([\w\d:#@%/;$()~_?\+-=\\\.&])*" + FIND_DOMAIN + "+([\w\d:#@%/;$()~_?\+-=\\\.&])*)")
114
      google_url_regex_result = google_url_regex.match(this_url)
115
      if google_url_regex_result:
116
        result = counter
117
        break
118
 
119
    return result
120
 
121
  def find_google_position(self, search_string):
122
    ENGINE_URL = 'http://www.google' + LOCALE + '/search?q=' + search_string.replace(' ', '+') + '&num=' + str(NUM_PER_PAGE)
123
    # print ENGINE_URL
124
 
125
    # run curl:
126
    for i in range(0, MAX_PAGE):
127
      position = self.search_page(i, ENGINE_URL)
128
      time.sleep(random.randint(0, self.pageSleep))
129
 
130
      if position != 0:
131
        break
132
 
133
    if position ==-1:
134
      return
135
    if position == 0:
136
      position = NUM_PER_PAGE * MAX_PAGE
137
 
138
    self.results.append((position, ((position-1)/10 + 1), search_string))
139
    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)
140
 
141
  def getDbConnection(self):
142
    return MySQLdb.connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
143
 
144
  def closeConnection(self, conn):
145
    conn.close()
146
 
147
  def loadSearchStringsFromDb(self):
148
    conn = self.getDbConnection()
149
 
150
    # Prepare SQL query to INSERT a record into the database.
151
    sql = "SELECT query FROM query where is_active = 1"
152
    try:
153
      # prepare a cursor object using cursor() method
154
      cursor = conn.cursor()
155
      # Execute the SQL command
156
      cursor.execute(sql)
157
      # Fetch all the rows in a list of lists.
158
      results = cursor.fetchall()
159
      for row in results:
160
        self.searchStrings.append(row[0])
161
      cursor.close()
162
    except Exception as e:
163
      print "Error: unable to fetch data"
164
      print e
165
 
166
    self.closeConnection(conn)
167
 
168
  def pushResultsToDb(self):
169
    conn = self.getDbConnection()
170
 
171
    try:
172
      # prepare a cursor object using cursor() method
173
      cursor = conn.cursor()
174
 
175
      cursor.executemany (
176
          """
177
              insert into rank(query_id, date, position, page) 
178
              select id , now(), %s, %s from query where query = %s;
179
          """, self.results)
180
      conn.commit()
181
      self.results = []
182
      cursor.close()
183
    except Exception as e:
184
      print "Error: unable to insert row"
185
      print e
186
 
187
    self.closeConnection(conn)
188
 
189
 
190
 
191
def main():
192
  if len(sys.argv) > 1:
193
    rank_cheker = RankCheck(0, 0)
194
    rank_cheker.addSearchStrings(sys.argv[1:])
195
  else:
196
    rank_cheker = RankCheck()
197
    rank_cheker.loadSearchStringsFromDb()
198
    rank_cheker.db_mode = True
199
 
200
  rank_cheker.start()
201
 
202
if __name__ == '__main__':
203
    main()