python-ox/ox/web/duckduckgo.py

23 lines
737 B
Python
Raw Normal View History

2010-12-29 17:36:14 +05:30
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
import re
2014-09-30 21:04:46 +02:00
from six.moves import urllib
2010-12-29 17:36:14 +05:30
import ox
from ox import strip_tags, decode_html
from ox.cache import read_url
2010-12-29 17:36:14 +05:30
def find(query, timeout=ox.cache.cache_timeout):
2014-09-30 21:04:46 +02:00
if not isinstance(query, bytes):
2010-12-31 12:53:24 +05:30
query = query.encode('utf-8')
2014-09-30 21:04:46 +02:00
params = urllib.parse.urlencode({'q': query})
2010-12-29 17:36:14 +05:30
url = 'http://duckduckgo.com/html/?' + params
2013-06-01 13:21:13 +02:00
data = read_url(url, timeout=timeout).decode('utf-8')
2010-12-29 17:36:14 +05:30
results = []
2013-06-01 12:25:20 +02:00
regex = '<a .*?class="large" href="(.+?)">(.*?)</a>.*?<div class="snippet">(.*?)</div>'
2010-12-29 17:36:14 +05:30
for r in re.compile(regex, re.DOTALL).findall(data):
results.append((strip_tags(decode_html(r[1])), r[0], strip_tags(decode_html(r[2]))))
2010-12-29 17:36:14 +05:30
return results