如何使用beautifulsoup 从(可能)损坏的html 中过滤掉.mp3 链接? (JSON)
·
问题:如何使用beautifulsoup 从(可能)损坏的html 中过滤掉.mp3 链接? (JSON)
我想构建一个小工具来帮助家庭成员从网站上下载播客。
为了获得指向文件的链接,我首先需要将它们过滤掉(使用 bs4 + python3)。文件在这个网站上(爱沙尼亚语):下载页面"Laadi alla" u003d "Download"
到目前为止,我的代码如下:(大部分来自stackoverflow上的示例)
from bs4 import BeautifulSoup
import urllib.request
import re
url = urllib.request.urlopen("http://vikerraadio.err.ee/listing/mystiline_venemaa#?page=1&pagesize=902&phrase=&from=&to=&path=mystiline_venemaa&showAll")
content = url.read()
soup = BeautifulSoup(content, "lxml")
links = [a['href'] for a in soup.find_all('a',href=re.compile('http.*\.mp3'))]
print ("Links:", links)
不幸的是,我总是只得到两个结果。输出:
Links: ['http://heli.err.ee/helid/exp/ERR_raadiouudised.mp3', 'http://heli.err.ee/helid/exp/ERR_raadiouudised.mp3']
这些不是我想要的。我最好的猜测是该页面的 html 和 bs4 有点损坏/解析器无法找到其他任何东西。我尝试了不同的解析器,结果没有任何变化。也许我也做错了什么。
例如,我的目标是将各个链接放在列表中。我稍后会自己过滤掉任何重复/不需要的条目。
只是一个简短的说明,以防万一:这是一个公共广播,所有内容都是合法托管的。
我的新代码是:
for link in soup.find_all('d2p1:DownloadUrl'):
print(link.text)
我非常不确定标签是否选择正确。
** this question 中列出的示例都没有实际工作。有关工作代码,请参阅下面的答案。**
解答
请注意,页面中的列表是通过API连接的。因此,我建议您请求具有 200 个 .mp3 链接的 API 链接,而不是请求 HTML 页面。
请按照以下步骤操作:
1.请求API链接,不是HTML页面链接
-
检查响应,它是 JSON。因此,提取您需要的字段
-
帮助您的家人,无时无刻:)
解决方案
import requests, json
from bs4 import BeautifulSoup
myurl = 'http://vikerraadio.err.ee/api/listing/bypath?path=mystiline_venemaa&page=1&pagesize=200&phrase=&from=&to=&showAll=false'
r = requests.get(myurl)
abc = json.loads(r.text)
all_mp3 = {}
for lstngs in abc['ListItems']:
for asd in lstngs['Podcasts']:
all_mp3[asd['DownloadUrl']] = lstngs['Header']
all_mp3
all_mp3 是您所需要的。 all_mp3 是一个字典,其中 download url 作为键,_mp3 名称 作为值。
更多推荐
所有评论(0)