您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)利用Python怎么獲取彈幕數(shù)據(jù),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
import zlib from bs4 import BeautifulSoup with open(r"C:\Users\HP\Downloads\6024766870349300_300_10.z", 'rb') as fin: content = fin.read() btArr = bytearray(content) xml=zlib.decompress(btArr).decode('utf-8') bs = BeautifulSoup(xml,"xml") bs
輸出
因此tvid只要獲得就能輕松獲取該電視劇的彈幕文件數(shù)據(jù)。
import zlib from bs4 import BeautifulSoup import pandas as pd import requests def get_data(tv_name,tv_id): """ 獲取每集的tvid :param tv_name: 集數(shù),第1集、第2集... :param tv_id: 每集的tvid :return: DataFrame, 最終的數(shù)據(jù) """ base_url = 'https://cmts.iqiyi.com/bullet/{}/{}/{}_300_{}.z' # 新建一個(gè)只有表頭的DataFrame head_data = pd.DataFrame(columns=['uid','contentsId','contents','likeCount']) for i in range(1,20): url = base_url.format(tv_id[-4:-2],tv_id[-2:],tv_id,i) print(url) res = requests.get(url) if res.status_code == 200: btArr = bytearray(res.content) xml=zlib.decompress(btArr).decode('utf-8') # 解壓壓縮文件 bs = BeautifulSoup(xml,"xml") # BeautifulSoup網(wǎng)頁解析 data = pd.DataFrame(columns=['uid','contentsId','contents','likeCount']) data['uid'] = [i.text for i in bs.findAll('uid')] data['contentsId'] = [i.text for i in bs.findAll('contentId')] data['contents'] = [i.text for i in bs.findAll('content')] data['likeCount'] = [i.text for i in bs.findAll('likeCount')] else: break head_data = pd.concat([head_data,data],ignore_index = True) head_data['tv_name']= tv_name return head_data
上文已通過tvid獲取到了彈幕文件數(shù)據(jù),那么如何獲取tvid又變成了一個(gè)問題。莫急,我們繼續(xù)分析。直接Ctrl + F搜索tvid
因此可以直接從返回結(jié)果中通過正則表達(dá)式獲取tvid。
from requests_html import HTMLSession, UserAgent from bs4 import BeautifulSoup import re def get_tvid(url): """ 獲取每集的tvid :param url: 請求網(wǎng)址 :return: str, 每集的tvid """ session = HTMLSession() #創(chuàng)建HTML會話對象 user_agent = UserAgent().random #創(chuàng)建隨機(jī)請求頭 header = {"User-Agent": user_agent} res = session.get(url, headers=header) res.encoding='utf-8' bs = BeautifulSoup(res.text,"html.parser") pattern =re.compile(".*?tvid.*?(\d{16}).*?") # 定義正則表達(dá)式 text_list = bs.find_all(text=pattern) # 通過正則表達(dá)式獲取內(nèi)容 for t in range(len(text_list)): res_list = pattern.findall(text_list[t]) if not res_list: pass else: tvid = res_list[0] return tvid
由此問題tvid。來每一集都有一個(gè)tvid,有多少集電視劇就可以獲取多少個(gè)tvid。那么問題又來了:獲取tvid時(shí),是通過url發(fā)送請求,從返回結(jié)果中獲取。而每一集的url又該如何獲取呢。
通過元素選擇工具定位到集數(shù)選擇信息。通過硒模擬瀏覽器獲取動態(tài)加載信息。
有小伙伴會說,可以直接直接從返回內(nèi)容中獲取此href網(wǎng)址啊,你可以自己動手嘗試下。
云朵君嘗試后得到的結(jié)果是href="javascript:void(0);" rel="external nofollow" ,因此解決這一問題的方法之一是運(yùn)用硒模擬瀏覽器獲取js動態(tài)加載信息。
def get_javascript0_links(url, class_name, class_name_father, sleep_time=0.02): """ Selenium模擬用戶點(diǎn)擊爬取url :param url: 目標(biāo)頁面 :param class_name: 模擬點(diǎn)擊的類 :param class_name_father: 模擬點(diǎn)擊的類,此類為class_name的父類 :param sleep_time: 留給頁面后退的時(shí)間 :return: list, 點(diǎn)擊class為class_name進(jìn)去的超鏈接 """ def wait(locator, timeout=15): """等到元素加載完成""" WebDriverWait(driver, timeout).until(EC.presence_of_element_located(locator)) options = Options() # options.add_argument("--headless") # 無界面,若你需要查看界面內(nèi)容,可以將此行注釋掉 driver = webdriver.Chrome(options=options) driver.get(url) locator = (By.CLASS_NAME, class_name) wait(locator) element = driver.find_elements_by_class_name(class_name_father) elements = driver.find_elements_by_class_name(class_name) link = [] linkNum = len(elements) for j in range(len(element)): wait(locator) driver.execute_script("arguments[0].click();", element[j]) # 模擬用戶點(diǎn)擊 for i in range(linkNum): print(i) wait(locator) elements = driver.find_elements_by_class_name(class_name) # 再次獲取元素,預(yù)防StaleElementReferenceException driver.execute_script("arguments[0].click();", elements[i]) # 模擬用戶點(diǎn)擊 time.sleep(sleep_time) link.append(driver.current_url) time.sleep(sleep_time) driver.back() driver.quit() return link if __name__ == "__main__": url = "https://www.iqiyi.com/v_1meaw5kgh4s.html" class_name = "qy-episode-num" link = get_javascript0_links(url, class_name, class_name_father="tab-bar") for i, _link in enumerate(link): print(i, _link)
接下來通過主函數(shù)將所有步驟串起。
def main(sleep_second=0.02): url = "https://www.iqiyi.com/v_1meaw5kgh4s.html" class_name = "select-item" class_name_father = "bar-li" links = get_javascript0_links(url, class_name, class_name_father) head_data = pd.DataFrame(columns=['tv_name','uid','contentsId','contents','likeCount']) for num, link in enumerate(links): tv_name = f"第{num+1}集" tv_id = get_tvid(url=link) data = get_data(tv_name,tv_id) head_data = pd.concat([head_data,data],ignore_index = True) time.sleep(sleep_second) return head_data
獲取到的數(shù)據(jù)結(jié)果如下:
>>> data = main() >>> data.info() """ <class 'pandas.core.frame.DataFrame'> RangeIndex: 246716 entries, 0 to 246715 Data columns (total 5 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 tv_name 246716 non-null object 1 uid 246716 non-null object 2 contentsId 246716 non-null object 3 contents 246716 non-null object 4 likeCount 246716 non-null object dtypes: object(5) memory usage: 9.4+ MB """ >>> data.sample(10)
運(yùn)用中文分詞庫jieba分詞,并去除撤銷詞。
def get_cut_words(content_series): """ :param content_series: 需要分詞的內(nèi)容 :return: list, 點(diǎn)擊class為class_name進(jìn)去的超鏈接 """ # 讀入停用詞表 import jieba stop_words = [] with open("stop_words.txt", 'r', encoding='utf-8') as f: lines = f.readlines() for line in lines: stop_words.append(line.strip()) # 添加關(guān)鍵詞 my_words = ['倪妮', '劉詩詩', '鎖鎖', '蔣三歲', '陳道明'] for i in my_words: jieba.add_word(i) # 自定義停用詞 my_stop_words = ['哈哈哈','哈哈哈哈', '真的'] stop_words.extend(my_stop_words) # 分詞 word_num = jieba.lcut(content_series.str.cat(sep='。'), cut_all=False) word_num_selected = [i for i in word_num if i not in stop_words and len(i)>=2] # 條件篩選 return word_num_selected
運(yùn)用升級版詞云圖庫stylecloud可視化彈幕結(jié)果。
import stylecloud from IPython.display import Image text1 = get_cut_words(content_series=data.contents) stylecloud.gen_stylecloud(text=' '.join(text1), collocations=False, font_path=r'?C:\Windows\Fonts\msyh.ttc', icon_name='fas fa-rocket',size=400, output_name='流金歲月-詞云.png') Image(filename='流金歲月-詞云.png')
看完上述內(nèi)容,你們對利用Python怎么獲取彈幕數(shù)據(jù)有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。