【问题标题】:How to get video src using BeautifulSoup in Python如何在 Python 中使用 BeautifulSoup 获取视频 src
【发布时间】:2020-09-30 19:13:42
【问题描述】:

我正在尝试在网站中查找可下载的视频链接。例如,我正在使用像 https://www.loc.gov/item/2015669100/ 这样的网址。可以看到mejs__mediaelementdiv标签下有一个m3u8视频链接。

但是我的代码没有打印任何东西。这意味着它没有找到该网站的视频网址。

我的代码在下面

from bs4 import BeautifulSoup
from urllib.request import Request, urlopen

with open('pages2crawl.txt', 'r') as inFile:
        lines = [line.rstrip() for line in inFile]

for page in lines:
        req = Request(page, headers={'User-Agent': 'Mozilla/5.0'})
        soup = BeautifulSoup(urlopen(req).read(), 'html.parser')
        pages = soup.findAll('div', attrs={'class' : 'mejs__mediaelement'})
        for e in pages:
                video = e.find("video").get("src")
                if video.endswith("m3u8"):
                        print(video)

【问题讨论】:

  • 您的问题是,您的 serached div 标签将不会交付(给我)。我可以看到一个 m3u8 文件,但没有一个父母是这个给定类的 div(在浏览器中我看到这个 div)。由于用户代理,您可能会获得浏览器以外的其他数据。您必须查看答案才能找到另一种定位方式,或尝试获取与浏览器相同的数据

标签: python python-3.x beautifulsoup


【解决方案1】:

如果您只想制作一个简单的脚本,使用正则表达式可能会更容易。

import re, requests

s = requests.Session() #start the session
data = s.get(url) #http get request to download data
data = data.text #get the raw text

vidlinks = re.findall("src='(.*?).m3u8'/>", data) #find all between the two parts in the data
print(vidlinks[0] + ".m3u8") #print the full link with extension

【讨论】:

    【解决方案2】:

    您可以使用 CSS 选择器 source[type="application/x-mpegURL"] 提取 MPEG 链接(或使用 source[type="video/mp4"] 提取 mp4 链接):

    import requests
    from bs4 import BeautifulSoup
    
    url = "https://www.loc.gov/item/2015669100/"
    soup = BeautifulSoup(requests.get(url).content, "html.parser")
    
    link_mpeg = soup.select_one('source[type="application/x-mpegURL"]')["src"]
    link_mp4 = soup.select_one('source[type="video/mp4"]')["src"]
    print(link_mpeg)
    print(link_mp4)
    

    打印:

    https://tile.loc.gov/streaming-services/iiif/service:afc:afc2010039:afc2010039_crhp0001:afc2010039_crhp0001_mv04/full/full/0/full/default.m3u8
    https://tile.loc.gov/storage-services/service/afc/afc2010039/afc2010039_crhp0001/afc2010039_crhp0001_mv04.mp4
    

    【讨论】:

    猜你喜欢
    • 2021-02-16
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 2022-08-07
    • 2021-11-20
    • 2021-08-17
    • 2020-12-03
    • 1970-01-01
    相关资源
    最近更新 更多