能夠看到一個DIV下放一個廣播劇的信息,包括名稱和地址,第一步咱們先收集全部廣播劇的收聽地址:html
# 用requests的get方法訪問
novel_list_resp = requests.get("這裏放URL的地址")
# 利用上一步訪問返回的結果生成一個BeautifulSoup對象
opera_soup = BeautifulSoup(novel_list_resp.text, "lxml")
# 獲取全部class="program-item"的div
opera_soup.find_all("div", class_="program-item")git
接着咱們遍歷這些div,獲取每一個廣播劇的連接和名稱:
# 找到div中的a標籤,獲取每一個廣播劇的連接
opera_link = domain + div.find("a").get('href')
# 獲取每一個廣播劇的名稱
title = div.find("div", class_="title").stringgithub
咱們點擊一個廣播劇進去,在HTML中能夠看到在ul中,每一個li裏都有一集的播放連接,而且是按順序的。dom
代碼中咱們繼續用以前的方法訪問單個廣播劇地址,來獲取劇集的list:
# 訪問單個廣播劇頁面
novel_view_resp = requests.get(opera_link)
# 利用上一步訪問返回的結果生成一個BeautifulSoup對象
view_soup = BeautifulSoup(novel_view_resp.text, "lxml")
# 首先定位h2標籤,而後獲取h2的下一個ul標籤(直接找ul的話會找到其餘的ul),而後獲取全部a標籤
list_a = view_soup.find('h2').find_next_sibling('ul').find_all('a')
# 接着遍歷a標籤,把每集的地址取出來
view_link = domain + a.get('href')編碼
咱們繼續看一個單集的播放的HTML,source標籤裏就是最終的資源地址了,一個MP4文件:url
# 打開單集的播放頁面
play_resp = requests.get(view_link)
play_soup = BeautifulSoup(play_resp.text, "lxml")
# 獲取資源下載地址
src = play_soup.find('source').attrs['src']3d
如今我還不想下載,我但願先試聽確認喜歡後再下載,因此我把下載地址存到一個txt裏,一個廣播劇存一個txt:
name = file_path + name + '.txt'
with open(name, 'wb') as f:
f.write(content)xml
因爲編碼問題,在文件最上加上如下代碼:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')htm
運行效果:對象
下載的MP4的代碼:
# 使用requests的get方法訪問下載連接
r = requests.get(url)
# 將訪問返回二進制數據內容保存爲MP4文件
with open(name, 'wb') as f:
f.write(r.content)
最終的運行結果:
源碼地址:https://github.com/songzhenhua/rti_opera/blob/master/rti_opera.py
BeautifulSoup參考地址:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#attributeshttp://www.cnblogs.com/zhaof/p/6930955.html