Python - Web 目录文件名 return 空白(请求 & BeautifulSoup)

Python - Web directory file names return blank (Requests & BeautifulSoup)

使用 Requests 和 BeautifulSoup 插件,我试图从特定的 Web 目录中检索所有 mp3 文件名,但它没有返回任何内容。

这是我运行的函数,其中包含问题:

archive_url = "http://example.com/audio/"

def get_video_links():

    r = requests.get(archive_url) 
    soup = BeautifulSoup(r.content,'html5lib')  
    links = soup.findAll('a') 
    video_links = [archive_url + link['href'] for link in links if link['href'].endswith('mp3')] 
    
    return video_links 

它没有正常运行,所以为了找出问题我 运行 print(video_links) 命令行只输出 []。它没有返回任何内容。我唯一的想法是我可能没有正确安装插件,不应该使用 Visual Studio 2019,或者需要以不同的方式配置项目。谁能看出我的愚蠢?我虚心征求意见。

(I am attempting to follow this tutorial)

首先,我建议将所需的模块上传到 运行 提供的函数:

import requests 
import bs4
from bs4 import BeautifulSoup 

然后,重新定义函数get_video_links(),当输出video_links是一个列表时,returns一个列表:

def get_video_links(archive_url):

    r = requests.get(archive_url) 
    soup = BeautifulSoup(r.content,'html5lib')  
    links = soup.findAll('a') 
    
# ensure to pass a list
    video_links = [archive_url + link['href'] for link in links if link['href'].endswith('mp3')] 
     
    if isinstance(video_links, list):
         return video_links
    else:
        raise AttributeError:
         return("video_links is not a list, convert to list")
    

    return video_links 

然后,定义函数的输入并直接从函数调用它,而不是使用 print(video_links),它是一个空列表,因为它没有在代码中定义:

archive_url = "http://example.com/audio/"
video_links=get_video_links(archive_url=archive_url)

简而言之:

# importing required modules

import requests 
import bs4
from bs4 import BeautifulSoup 

# define function to get the video links:
# input: a list built-in
def get_video_links(archive_url):

    r = requests.get(archive_url) 
    soup = BeautifulSoup(r.content,'html5lib')  
    links = soup.findAll('a') 
    
# ensure to pass a list
    video_links = [archive_url + link['href'] for link in links if link['href'].endswith('mp3')] 
     
    if isinstance(video_links, list):
         return video_links
    else:
        raise AttributeError:
            print("video_links is not a list, convert to list")
    

    return video_links 

# set input and call it in the function

archive_url = "http://example.com/audio/"
video_links=get_video_links(archive_url=archive_url)