Added site keyword, added unique user agent

This commit is contained in:
2016-02-03 16:45:57 +08:00
parent 9aa18469b7
commit 5069862d8d
3 changed files with 22 additions and 8 deletions
+12 -1
View File
@@ -59,6 +59,18 @@ Note: `compleat.suggest()` also accepts an optional `lang` parameter, which is "
['bonoloto', 'bonus', 'bon jovi', 'bones', 'bonsai']
```
Note: `compleat.suggest()` also accepts an optional `site` parameter, which is "" (Google) by default. Others include `bo` for google books, `i` for google images, and `yt` for youtube.
```python
>>> import compleat
>>> [ s["text"] for s in compleat.suggest("bon", site="yt").suggestions[:5] ]
['bon jovi', 'bone thugs n harmony', 'bonetrousle', 'bones', 'bon iver']
>>> [ s["text"] for s in compleat.suggest("bon", site="bo").suggestions[:5] ]
['bone', 'bonhoeffer', 'bonnie and clyde', 'bond', 'bonsai']
>>> [ s["text"] for s in compleat.suggest("bon", site="i").suggestions[:5] ]
['bonnie wright', 'bonnie and clyde', 'bonsai', 'bong', 'bone']
```
### Command-line tool
Run `compleat -h` from the command line for full set of options. Examples:
@@ -72,4 +84,3 @@ Run `compleat -h` from the command line for full set of options. Examples:
`compleat -q "who is " "why is " "where is "`
`compleat --template "is {} " -q "allen iverson" "marie curie" "meryl streep"`
+2 -2
View File
@@ -3,5 +3,5 @@ from .query import Query
VERSION = (0, 0, 2)
__version__ = ".".join(map(str,VERSION))
def suggest(query_string, lang="en"):
return Query(query_string, lang)
def suggest(query_string, lang="en", site="",):
return Query(query_string, lang, site)
+8 -5
View File
@@ -6,13 +6,14 @@ import datetime
import random
class Query(object):
URL_TEMPLATE = "http://suggestqueries.google.com/complete/search?client=chrome&hl={lang}&q={query}"
def __init__(self, query, lang="en"):
URL_TEMPLATE = "http://suggestqueries.google.com/complete/search?client=chrome&hl={lang}&q={query}&ds={site}"
def __init__(self, query, lang="en", site=""):
self.query = query
self.lang = lang
self.site = site
self.timestamp = datetime.datetime.now()
self.rand = str(random.random())
req = requests.get(self.url)
req = requests.get(self.url, headers={'User-Agent': requests.utils.default_user_agent() + '/r=' + self.rand})
self.response = req.json()
@property
@@ -21,7 +22,8 @@ class Query(object):
escaped = urllib.parse.quote(encoded)
return self.URL_TEMPLATE.format(
query=escaped,
lang=self.lang)
lang=self.lang,
site=self.site)
@property
def suggestions(self):
@@ -55,5 +57,6 @@ class Query(object):
"query": self.query,
"lang": self.lang,
"timestamp": self.timestamp.ctime(),
"uid": self.uid
"uid": self.uid,
"site": self.site,
}