我正在嘗試通過網路抓取 YouTube 視頻串列,并且我想收集每個視頻的 YouTube 描述。但是,我不成功,不明白為什么會這樣。任何幫助深表感謝。(有問題的 Youtube 視頻:https ://www.youtube.com/watch?v=57Tjvv_pCXg&t=55s )
element_titles = driver.find_elements_by_id("video-title")
result = requests.get(element_titles[1].get_attribute("href"))
soup = BeautifulSoup(result.content)
description = str(soup.find("div", {"class": "style-scope yt-formatted-string"}))
描述的結果是None
注意 我了解存在 Youtube API,但是您必須為 API 密鑰付費,這樣做不符合我的利益
uj5u.com熱心網友回復:
要提取描述,您可以同時使用 selenium 或 beautifulsoup。后者更快,這里是代碼
import re
soup = BeautifulSoup(requests.get('https://www.youtube.com/watch?v=57Tjvv_pCXg').content)
pattern = re.compile('(?<=shortDescription":").*(?=","isCrawlable)')
description = pattern.findall(str(soup))[0].replace('\\n','\n')
print(description)
如果你運行print(soup.prettify())并查找視頻描述的一部分,比如說know this is just my,你會看到完整的描述在一個大的 json 結構中
...,"isOwnerViewing":false,"shortDescription":"Listen: https://quellechris360.bandcamp.com/album/deathfame\n\nQuelle Chris delivers what might be his most challengi...bla bla...ABSTRACT HIP HOP\n\n7/10\n\nY'all know this is just my opinion, right?","isCrawlable":true,"thumbnail":{...
特別是描述包含在shortDescription":"和之間","isCrawlable,因此我們可以使用正則運算式來提取這兩個字串之間包含的子字串。.*查找兩個字串之間包含的每個字符 ( ) 的正則運算式命令是(?<=shortDescription":").*(?=","isCrawlable)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/480824.html
