【问题标题】:Downloading all Images from a page with beautifulSoup not working使用 beautifulSoup 从页面下载所有图像不起作用
【发布时间】:2022-11-06 07:44:38
【问题描述】:

我正在尝试使用 beautifulsoup 从this 页面下载节目图片。

当我运行下面的代码时,唯一下载的图像是旋转加载图标。

当我检查页面上的请求选项卡时,我可以看到页面上所有其他图像的请求,因此假设它们也应该被下载。我不确定为什么它们不会下载,因为它们包含在页面上 html 的 img 标签中?

import re
import requests
from bs4 import BeautifulSoup
site = 'https://www.tvnz.co.nz/categories/sci-fi-and-fantasy'
response = requests.get(site)
soup = BeautifulSoup(response.text, 'html.parser')
image_tags = soup.find_all('img')
urls = [img['src'] for img in image_tags]
for url in urls:
    filename = re.search(r'/([\w_-]+[.](jpg|gif|png))$', url)
    if not filename:
         print("Regular expression didn't match with the url: {}".format(url))
         continue
    with open(filename.group(1), 'wb') as f:
        if 'http' not in url:
            url = '{}{}'.format(site, url)
        response = requests.get(url)
        f.write(response.content)
print("Download complete, downloaded images can be found in current directory!")

【问题讨论】:

  • 看起来页面是使用 JavaScript 加载的。如果您运行print(response.text),您会注意到 HTML 不包含电视节目。你需要像硒这样的东西
  • 注意到,感谢将研究 Selenium。是否可以只发布请求以获取相同的图像?使用 python 请求库?

标签: python beautifulsoup


【解决方案1】:

您可以尝试通过他们似乎用来填充页面的 api

api_url = 'https://apis-edge-prod.tech.tvnz.co.nz/api/v1/web/play/page/categories/sci-fi-and-fantasy'
r = requests.get(api_url)
try:
    embVals = r.json()['_embedded'].values() 
except Exception as e:
    embVals = []
    print('failed to get embedded items
', str(e))

urls = [img for images in [ [
    v['src'] for k, v in ev.items() if 
    k is not None and ('image' in k or 'Image' in k) 
    and v is not None and 'src' in v
] for ev in embVals] for img in images]

# for url in urls: # should work the same

(图像似乎在嵌套字典中,带有'portraitTileImage'、'image'、'tileImage'、'coverImage'等键。您也可以使用 for-loop/s 遍历embVals 并提取其他数据,如果你想在文件名/元数据/等中包含更多内容。)

我不知道它是否会为您提供页面上的所有图像,但当我尝试它时,urls 有 297 个链接。

【讨论】:

    猜你喜欢
    • 2020-11-25
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    相关资源
    最近更新 更多