我正在构建一个脚本,使用请求和BeautifulSoup从指定的gyfycat网页下载一个.mp4文件。我遇到了一个错误,无法访问源标记的'src'
属性。我的目标是以下HTML元素:
<source src="https://giant.gfycat.com/PoshDearAsianporcupine.mp4" type="video/mp4">
当我分别用'a'
和'href'
替换标记和属性时,我的代码可以工作,所以我不知道为什么我不能访问这个
'src'
属性。代码如下:
import requests
from bs4 import BeautifulSoup
gyfyUrl = 'https://gfycat.com/PoshDearAsianporcupine'
# creating a response object
r = requests.get(gyfyUrl)
# creating beautiful soup object
soup = BeautifulSoup(r.content,'html5lib')
# finding source tags in page
sourceTags = soup.findAll('source')
#printing found tags for clarity
print(sourceTags)
# printing src attribute within source tags - Error
for tag in sourceTags:
print(tag['src'])
这里的问题是不是每个
source
标记都有src
属性,在本例中,第一个标记没有。您可以使用如下条件列表理解来收集所有src
属性(如果存在):结果:
相关问题 更多 >
编程相关推荐