forked from ravivmg/google-scholar-search
-
Notifications
You must be signed in to change notification settings - Fork 0
/
google_search.py
238 lines (210 loc) · 9.2 KB
/
google_search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import httplib
import urllib
import urlparse
from BeautifulSoup import BeautifulSoup
import re
import time
import hashlib
import os
class GoogleScholarSearch:
def __init__(self):
self.SEARCH_HOST = "scholar.google.com"
self.SEARCH_BASE_URL = "/scholar"
def get_page_fields(self, html):
results = []
# Screen-scrape the result to obtain the publication information
soup = BeautifulSoup(html)
for record in soup('div', {'class': 'gs_r'}):
# Includeds error checking
topPart = record.first('h3')
# get article url
pubURL = ""
if topPart.a:
pubURL = topPart.a['href']
# Clean up the URL, make sure it does not contain '\' but '/' instead
pubURL = pubURL.replace('\\', '/')
# get download pdf url
downloadPart = record.first('span')
downloadURL = ""
if downloadPart.a:
downloadURL = downloadPart.a['href']
# Clean up the URL, make sure it does not contain '\' but '/' instead
downloadURL = downloadURL.replace('\\', '/')
pubTitle = ""
if topPart.a:
for part in topPart.a.contents:
pubTitle += str(part.string)
if pubTitle == "":
pubTitle = topPart.text.strip()
authorPart = record.first('span', {'class': 'gs_a'}).string
if authorPart == None:
authorPart = re.search('<span class="gs_a">(.*?)</span>',str(record)).group(1)
num = authorPart.count(" - ")
# Assume that the fields are delimited by ' - ', the first entry will be the
# list of authors, the last entry is the journal URL, anything in between
# should be the journal year
idx_start = authorPart.find(' - ')
idx_end = authorPart.rfind(' - ')
pubAuthors = authorPart[:idx_start]
tmpSearch = re.search('\d{4}',authorPart[idx_start + 3:idx_end])
pubJournalYear = ''
if tmpSearch:
pubJournalYear = tmpSearch.group(0)
pubJournalURL = authorPart[idx_end + 3:]
# If (only one ' - ' is found) and (the end bit contains '\d\d\d\d')
# then the last bit is journal year instead of journal URL
if pubJournalYear=='' and re.search('\d\d\d\d', pubJournalURL)!=None:
pubJournalYear = pubJournalURL
pubJournalURL = ''
match = re.search("Cited by ([^<]*)", str(record))
pubCitation = ''
if match != None:
pubCitation = match.group(1)
results.append({
"URL": pubURL,
"DOWNLOAD_URL": downloadURL,
"Title": pubTitle,
"Authors": pubAuthors,
"JournalYear": pubJournalYear,
"JournalURL": pubJournalURL,
"NumCited": pubCitation,
})
return results
# example
# http://scholar.google.com/scholar?hl=en&q=&as_publication=sigir&btnG=Search&as_sdt=0%2C5&as_ylo=2009&as_yhi=2011&as_vis=0
def advanced_search_publication(self, as_publication, from_year, to_year, start=0, limit=10):
results = []
while start+10<=limit:
last_results = len(results)
params = urllib.urlencode({'q': "", 'as_ylo': from_year, 'as_yhi': to_year, 'start': start,
'as_publication': as_publication, 'hl': 'en', 'btnG': 'Search'})
headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
url = self.SEARCH_BASE_URL+"?"+params
conn = httplib.HTTPConnection(self.SEARCH_HOST)
conn.request("GET", url, {}, headers)
resp = conn.getresponse()
if resp.status==200:
html = resp.read()
html = html.decode('ascii', 'ignore')
results.extend(self.get_page_fields(html))
else:
print "ERROR: ",
print resp.status, resp.reason
return []
start+=10
if (len(results) - last_results) == 0:
print "no additional results. break"
break
print start
time.sleep(3)
return results
def search_tearms(self, terms, limit=10):
start = 0
results = []
while start+10<=limit:
params = urllib.urlencode({'q': "+".join(terms),'as_yhi': 2008, 'start': start })
headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
url = self.SEARCH_BASE_URL+"?"+params
conn = httplib.HTTPConnection(self.SEARCH_HOST)
conn.request("GET", url, {}, headers)
resp = conn.getresponse()
if resp.status==200:
html = resp.read()
html = html.decode('ascii', 'ignore')
results.extend(self.get_page_fields(html))
else:
print "ERROR: ",
print resp.status, resp.reason
return []
start+=10
print start
time.sleep(3)
return results
def download_pdf(filename, download_url):
print "downloading... %s" % download_url
url = urlparse.urlparse(download_url)
if url.port:
conn = httplib.HTTPConnection(url.hostname, url.port)
else:
conn = httplib.HTTPConnection(url.hostname)
headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
conn.request("GET", url.path+"?"+url.query, {}, headers)
resp = conn.getresponse()
if resp.status==200:
data = resp.read()
fpdf = open(filename, "wb")
fpdf.write(data)
fpdf.close()
else:
print "ERROR during download pdf url"
ACM_EXPORTFORMATS_URL = '/exportformats.cfm'
ACM_DOWNFORMATS_URL = '/downformats.cfm'
ACM_EXPORTFORMATS_HOST = 'dl.acm.org'
def download_acm_bib(filename, acm_url):
print "downloading bibtex for... %s" % acm_url
# http://portal.acm.org/citation.cfm?id=1572060
# http://portal.acm.org/citation.cfm?id=1571941.1571963
acm_id = re.search(r'id=([\d\.]*)',str(acm_url)).group(1)
if '.' in acm_id:
acm_id = acm_id.split('.')[-1]
if not acm_id:
print "no acm id extracted"
return
print "acm id:", acm_id
params = urllib.urlencode({'expformat': 'bibtex', 'id': acm_id})
headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
url = ACM_EXPORTFORMATS_URL+"?"+params
time.sleep(2)
conn = httplib.HTTPConnection(ACM_EXPORTFORMATS_HOST)
conn.request("GET", url, {}, headers)
resp = conn.getresponse()
if resp.status==200:
html = resp.read()
parent_id = re.search(r'downformats.cfm\?id=[\d]*&parent_id=([\d]*)',str(html)).group(1)
print "parent_id: ", parent_id
params = urllib.urlencode({'expformat': 'bibtex', 'id': acm_id, 'parent_id': parent_id})
headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
url = ACM_DOWNFORMATS_URL+"?"+params
time.sleep(2)
conn = httplib.HTTPConnection(ACM_EXPORTFORMATS_HOST)
conn.request("GET", url, {}, headers)
resp = conn.getresponse()
print "response: ", resp.status
if resp.status==200:
data = resp.read()
fbib = open(filename, "wb")
fbib.write(data)
fbib.close()
else:
print "ERROR during download bibtex url"
DOWNLOAD_DIR = 'download'
if __name__ == '__main__':
search = GoogleScholarSearch()
pubs = search.advanced_search_publication('sigir', 2009, 2011, 0, 2000)
if not os.path.isdir(DOWNLOAD_DIR):
os.mkdir(DOWNLOAD_DIR)
for pub in pubs:
print pub['Title']
print pub['Authors']
print pub['JournalYear']
print pub['JournalURL']
print pub['NumCited']
print pub['URL']
print pub['DOWNLOAD_URL']
if pub['DOWNLOAD_URL']:
md5hex_filename = hashlib.md5(pub['URL']).hexdigest()[:8]
file_exists = os.path.isfile(os.path.join(DOWNLOAD_DIR, md5hex_filename+".txt"))
print "md5 hex: %s" % md5hex_filename
if not file_exists:
ftxt = open(os.path.join(DOWNLOAD_DIR, md5hex_filename+".txt"), "w")
for key, item in pub.iteritems():
ftxt.write("%s: %s\n" % (key, item))
ftxt.close()
# try download pdf
download_pdf(os.path.join(DOWNLOAD_DIR, md5hex_filename+".pdf"), pub['DOWNLOAD_URL'])
# try download bib file
if 'portal.acm.org' in pub['URL']:
download_acm_bib(os.path.join(DOWNLOAD_DIR, md5hex_filename+".bib"), pub['URL'])
else:
print "file with md5 %s already exists" % md5hex_filename
print "======================================"