【问题标题】:How to get absolute path for image on a website如何获取网站上图像的绝对路径
【发布时间】:2016-10-18 14:03:38
【问题描述】:

在 Firefox 中,可以右键单击图像并选择“复制图像位置”。即使在图像的 src 属性中仅提供相对路径,这也允许获取绝对图像路径。 是否可以通过编程方式获取此绝对路径?它存储在哪里?

我用Python3,请求访问网站,美汤解析html。

【问题讨论】:

  • 页面是什么?
  • 这里 src 属性可以是完整的 url、当前页面的相对路径、域的相对路径,甚至可以向上移动到父目录,如 src="../some_folder 和许多其他变体,有没有一种方法可以神奇地获得 bs4 的完整路径,它不是浏览器。
  • @PadraicCunningham 不幸的是,我可能不会给您检查页面地址,但同样,在我的情况下,url + image src 不是解决方案。我怀疑 bs4 无法处理它,它只解析纯 HTML。我希望完整路径存储在某个地方,Firefox 可以以某种方式计算它,我希望能够做到这一点。
  • @wasd,您的浏览器可以运行 js 并上下目录,所以这确实是不同的,使用 selenium 之类的东西可能更接近您想要的。

标签: python-3.x beautifulsoup python-requests relative-path absolute-path


【解决方案1】:

简单的解决方案

from bs4 import BeautifulSoup
from requests import get

url = 'https://example.com/'
response = get(url)
soup = BeautifulSoup(response.content, 'html.parser')

# converting to a set will prevent duplicates
images = set([img['src'] for img in soup.find_all('img') if hasattr(img, 'src')])

for img in images:
    print(img)

扩展解决方案

对于使用相对路径(或外部主机、cdn 等)的图像,我们可以使用下面的代码清除大部分。

注意:这在使用本地 URI (file:///temp/web/img1.png) 时不起作用

此代码使用validators 包,因此请使用pip install validators 安装

from bs4 import BeautifulSoup
from requests import get
from os.path import join, normpath
import validators

url = 'https://example.com/'
response = get(url)
soup = BeautifulSoup(response.content, 'html.parser')

images = set([img['src'] for img in soup.find_all('img') if hasattr(img, 'src')])

list_of_img_paths = []

for img in images:
    if not validators.url(url):  # If NOT a valid URL
        # Here we can assume we are dealing with a relative path
        formatted_url = normpath(join(url, img))  # format a valid url
        list_of_img_paths.append(formatted_url)  # add to list
    else:
        list_of_img_paths.append(img)

【讨论】:

  • 简单和扩展的解决方案都不是真正的答案:简单只给出相对路径,而扩展只假设完整路径是一个url +图像src,有时(在例如我的情况)是不正确的。
  • 我已更新我的答案以使用 os.path.normpath() 正确格式化当前目录上方的相对路径。 "https://example.com/a/b/c.html""../../img.jpg" 加入成为 "https://example.com/a/img.jpg"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多