import xml.etree.ElementTree as ET from urllib.request import urlopen ompl_radio_browse_url = 'http://opml.radiotime.com/Browse.ashx' def radio_name_cleanup(radio_name): """Removes tokens with brackets or points "Radio Bamberg 106.1 (Top 40/Pop)" -> "Radio Bamberg 106.1" """ radio_name = radio_name.split() res = [] for token in radio_name: if '(' in token or ')' in token: continue res.append(token) return " ".join(res) def get_sender_information(queryURL): """ Example Query: GET http://opml.radiotime.com/Browse.ashx?partnerId=&serial= partnerid and serial does not seem to be necessary - so we do not use it here, """ xmlfile = urlopen(queryURL) tree = ET.ElementTree(file=xmlfile) rootnode = tree.getroot() result = dict() for node in rootnode.iter('outline'): if 'type' not in node.attrib or node.attrib['type'] != "audio": continue station_name = radio_name_cleanup(node.attrib['text']) station_url = node.attrib['URL'] station_id = node.attrib['guide_id'] print(station_name) result[station_id] = {'name': station_name, 'url': station_url} return result def get_related_radio_stations(stationID): query_url = ompl_radio_browse_url + '?id=' + stationID return get_sender_information(query_url) def get_local_radio_stations(): # goto ompl.radiotime with parameter ?c=local and look for your city there then paste id here query_url = ompl_radio_browse_url + '?id=r100765' result = get_sender_information(query_url) return result def find_local_radio_url_by_name(search_name): """Searches at the Radiotime database for a local radiostation which contains the searchName """ search_name = search_name.lower().strip() if search_name.startswith('http'): return search_name # first try: find a station that starts with the search expression for radio_id, radio in find_local_radio_url_by_name.stations.items(): if radio['name'].lower().startswith(search_name): return radio['url'] # second try: containment is enough for radio_id, radio in find_local_radio_url_by_name.stations.items(): if search_name in radio['name'].lower(): return radio['url'] raise ValueError("Could not find radio station " + search_name) find_local_radio_url_by_name.stations = get_local_radio_stations() if __name__ == '__main__': print(find_local_radio_url_by_name("B 5 aktuell"))