bandcamp.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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(
  40. query=urlencode({'q': query}),
  41. page=params['pageno'])
  42. params['url'] = base_url + search_path
  43. return params
  44. def response(resp):
  45. '''post-response callback
  46. resp: requests response object
  47. '''
  48. results = []
  49. tree = html.fromstring(resp.text)
  50. search_results = tree.xpath('//li[contains(@class, "searchresult")]')
  51. for result in search_results:
  52. link = result.xpath('.//div[@class="itemurl"]/a')[0]
  53. result_id = parse_qs(urlparse(link.get('href')).query)["search_item_id"][0]
  54. title = result.xpath('.//div[@class="heading"]/a/text()')
  55. date = dateparse(result.xpath('//div[@class="released"]/text()')[0].replace("released ", ""))
  56. content = result.xpath('.//div[@class="subhead"]/text()')
  57. new_result = {
  58. "url": extract_text(link),
  59. "title": extract_text(title),
  60. "content": extract_text(content),
  61. "publishedDate": date,
  62. }
  63. thumbnail = result.xpath('.//div[@class="art"]/img/@src')
  64. if thumbnail:
  65. new_result['thumbnail'] = thumbnail[0]
  66. if "album" in result.classes:
  67. new_result["embedded"] = embedded_url.format(type='album', result_id=result_id)
  68. elif "track" in result.classes:
  69. new_result["embedded"] = embedded_url.format(type='track', result_id=result_id)
  70. results.append(new_result)
  71. return results