我可以下载延迟加载图像吗?

Can I download a lazy load image?

我正在尝试使用 urllib 从 tripadvisor 下载一些图片,但我从 html 的 src 字段中为 url 获得的所有图片都是 this

我做了一些研究,发现那些是延迟加载图像...有什么办法可以下载它们吗??

您可以使用 Beautiful Soup and json 模块从 Javascript 中提取图像列表,然后遍历该列表并检索您感兴趣的图像。

编辑:

问题是图像具有相同的名称,所以它们被覆盖了。获取前三张图像是微不足道的,但是在轮播打开之前不会加载对轮播中其他图像的引用,所以这比较棘手。对于某些图像,您可以通过将路径中的 "photo-s" 替换为 "photo-w" 来找到更高分辨率的版本,但要弄清楚哪个需要更深入地研究 Javascript 逻辑。

import urllib, re, json
from bs4 import BeautifulSoup as bs

def img_data_filter(tag):
    if tag.name == "script" and tag.text.strip().startswith("var lazyImgs"):
        return True
    return False

response = urllib.urlopen("https://www.tripadvisor.it/Restaurant_Review-g3174493-d3164947-Reviews-Le_Ciaspole-Tret_Fondo_Province_of_Trento_Trentino_Alto_Adige.html")
soup = bs(response.read(), 'html.parser')
img_data = soup.find(img_data_filter)

js = img_data.text
js = js.replace("var lazyImgs = ", '')
js = re.sub(r";\s+var lazyHtml.+", '', js, flags=re.DOTALL)

imgs = json.loads(js)
suffix = 1

for img in imgs:
    img_url = img["data"]

    if not "media/photo-s" in img_url:
        continue

    img_name = img_url[img_url.rfind('/')+1:-4]
    img_name = "%s-%03d.jpg" % (img_name, suffix)
    suffix += 1

    urllib.urlretrieve(img_url, img_name)