gpt4 book ai didi

python - Beautifulsoup 从 html 中提取所有外部资源

转载 作者:行者123 更新时间:2023-11-27 23:41:13 25 4
gpt4 key购买 nike

我希望识别在 html 文件中请求外部资源的 url。

我目前在 imgscript 标签中使用 scr 属性,在link 标记(用于标识 css)。

我是否应该检查其他标签以识别其他资源?

作为引用,我的 Python 代码目前是:

html = read_in_file(file)
soup = BeautifulSoup(html)
image_scr = [x['src'] for x in soup.findAll('img')]
css_link = [x['href'] for x in soup.findAll('link')]
scipt_src = [] ## Often times script doesn't have attributes 'src' hence need for try/except
for x in soup.findAll('script'):
try:
scipt_src.append(x['src'])
except KeyError:
pass

最佳答案

更新了我的代码以捕获 html 代码中最常见的资源。显然,这不会查看 CSS 或 Javascript 中请求的资源。如果我缺少标签,请发表评论。

from bs4 import BeautifulSoup 
def find_list_resources (tag, attribute,soup):
list = []
for x in soup.findAll(tag):
try:
list.append(x[attribute])
except KeyError:
pass
return(list)

html = read_in_file(file)
soup = BeautifulSoup(html)

image_scr = find_list_resources('img',"src",soup)
scipt_src = find_list_resources('script',"src",soup)
css_link = find_list_resources("link","href",soup)
video_src = find_list_resources("video","src",soup)
audio_src = find_list_resources("audio","src",soup)
iframe_src = find_list_resources("iframe","src",soup)
embed_src = find_list_resources("embed","src",soup)
object_data = find_list_resources("object","data",soup)
soruce_src = find_list_resources("source","src",soup)

关于python - Beautifulsoup 从 html 中提取所有外部资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31666584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com