писал когда-то для себя на коленке. выкладываю as is
PHP код:
#!/usr/bin/env python
#coding=utf-8
import httplib,re,urlparse,traceback,random
from time import sleep
from os import system
from urllib import quote_plus, unquote_plus
#================ data ===============
language = 'en'
domain_google = "www.google.com"
url = '''http://%s/search?hl=%s&q={KEYW}&btnG=Search''' % (domain_google,language)
patt_rel = '''<a href="/search\?.*?ct=broad-revision.*?">(.*?)</a>'''
#
def save_rsl(keywords):
rsl = open(unquote_plus(kw_begin)+".txt","a+")
for i in keywords:
rsl.write(unquote_plus(i)+"\n")
rsl.close()
#================ code ===============
try:
for kwr in open("keywords.txt","r").read().splitlines():
kw_current = ""
kw_last = []
kw = []
kw_tosave = []
while 1:
kw_begin = kwr
if kw_current == "":
kw_current = kw_begin
elif kw_current == "none":
try:
kw_current = kw.pop(0)
while kw_current in kw_last:
kw_current = kw.pop(0)
except IndexError:
kw_current = ''
break
print "[*] Current kw: %s. Last kw: %d. Job: %d" %(kw_current,len(kw_last),len(kw))
url1 = url.replace("{KEYW}",quote_plus(kw_current))
up = urlparse.urlparse(url1)
conn = httplib.HTTPConnection(domain_google)
conn.connect()
conn.putrequest("GET", up.path+'?'+up.query)
conn.putheader("User-Agent", "Opera/9.63 (Windows NT 5.1; U; en) Presto/2.1.1")
conn.putheader("Accept","text/html, application/xml;q=0.9, application/xhtml+xml, image/png, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1")
conn.putheader("Accept-Language","en")
conn.putheader("Connection","Keep-Alive")
conn.endheaders()
r = conn.getresponse()
source = r.read()
#source = open("3.htm","r").read()
kw_new = re.findall(patt_rel,source,re.I)
kw_last.append(kw_current)
kw_tosave.append(kw_current)
if len(kw_tosave) % 50 == 0:
system("CLS")
save_rsl(kw_tosave)
kw_tosave = []
if kw_new != []:
for i in kw_new:
i = re.sub("<.*?>","",i)
i = re.sub('&#(\d+);', lambda x: chr(int(x.group(1))), i)
if i not in kw_last:
kw.append(i)
kw_current = "none"
continue
elif kw == []:
print "[*] All kw find!"
save_rsl(kw_tosave)
break
else:
print "[*] Not find kw on query:",kw_current
kw_current = "none"
continue
except KeyboardInterrupt:
save_rsl(kw_tosave)
for i in kw_last+kw_tosave:
try:
kw.remove(i)
except ValueError:
continue
save_rsl(kw)
except:
traceback.print_exc(file=open("log.txt","w"))
парсит related ссылки и следуя по ним собирает новые.
в файле keywords.txt ключевик на строчку.
остановить скрипт с сохранением результатов Ctrl+C
ps: не рекомендую чекать очень распространненые кеи, а то парсер "уйдет от темы". у меня так при исходнлм запросе russia конечный оказался deputy prime minister england
UPD: обновил. теперь можно собирать не только английские кейворды. язык можно задать в параметре
language.
UPD1: Добавил чистку дублей и кейвордов.