【发布时间】: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