bandcamp.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. """
  2. Bandcamp (Music)
  3. @website https://bandcamp.com/
  4. @provide-api no
  5. @results HTML
  6. @parse url, title, content, publishedDate, embedded, thumbnail
  7. """
  8. from urllib.parse import urlencode, urlparse, parse_qs
  9. from dateutil.parser import parse as dateparse
  10. from lxml import html
  11. from searx.utils import extract_text
  12. # about
  13. about = {
  14. "website": 'https://bandcamp.com/',
  15. "wikidata_id": 'Q545966',
  16. "official_api_documentation": 'https://bandcamp.com/developer',
  17. "use_official_api": False,
  18. "require_api_key": False,
  19. "results": 'HTML',
  20. }
  21. categories = ['music']
  22. paging = True
  23. base_url = "https://bandcamp.com/"
  24. search_string = search_string = 'search?{query}&page={page}'
  25. embedded_url = '''<iframe width="100%" height="166"
  26. scrolling="no" frameborder="no"
  27. data-src="https://bandcamp.com/EmbeddedPlayer/{type}={result_id}/size=large/bgcol=ffffff/linkcol=0687f5/tracklist=false/artwork=small/transparent=true/"
  28. ></iframe>'''
  29. def request(query, params):
  30. '''pre-request callback
  31. params<dict>:
  32. method : POST/GET
  33. headers : {}
  34. data : {} # if method == POST
  35. url : ''
  36. category: 'search category'
  37. pageno : 1 # number of the requested page
  38. '''
  39. search_path = search_string.format(query=urlencode({'q': query}), page=params['pageno'])
  40. params['url'] = base_url + search_path
  41. return params
  42. def response(resp):
  43. '''post-response callback
  44. resp: requests response object
  45. '''
  46. results = []
  47. tree = html.fromstring(resp.text)
  48. search_results = tree.xpath('//li[contains(@class, "searchresult")]')
  49. for result in search_results:
  50. link = result.xpath('.//div[@class="itemurl"]/a')[0]
  51. result_id = parse_qs(urlparse(link.get('href')).query)["search_item_id"][0]
  52. title = result.xpath('.//div[@class="heading"]/a/text()')
  53. date = dateparse(result.xpath('//div[@class="released"]/text()')[0].replace("released ", ""))
  54. content = result.xpath('.//div[@class="subhead"]/text()')
  55. new_result = {
  56. "url": extract_text(link),
  57. "title": extract_text(title),
  58. "content": extract_text(content),
  59. "publishedDate": date,
  60. }
  61. thumbnail = result.xpath('.//div[@class="art"]/img/@src')
  62. if thumbnail:
  63. new_result['thumbnail'] = thumbnail[0]
  64. if "album" in result.classes:
  65. new_result["embedded"] = embedded_url.format(type='album', result_id=result_id)
  66. elif "track" in result.classes:
  67. new_result["embedded"] = embedded_url.format(type='track', result_id=result_id)
  68. results.append(new_result)
  69. return results