【发布时间】:2020-05-21 01:15:16
【问题描述】:
我想使用 Python 创建一个网络爬虫,以创建我自己的狗图片和猫图片数据集。我想从以下站点抓取一定数量的图片:https://unsplash.com/images/animals/dog。
我遇到的问题是页面源没有显示所有图片,而不是来自 Inspect 元素的代码(包含所有 HTML、CSS 和 JavaScript)。如何获取完整的代码以抓取所有图像?我尝试使用 Selenium 和 Dryscrape,但没有成功......
这是我的代码:
#Import
import requests
from bs4 import BeautifulSoup
import urllib.request
import random
from google.colab import drive
#Directory
drive.mount('/content/drive')
data_dir = 'drive/My Drive/Colab Notebooks/Web scraper/Images/Dogs'
#Image scraper
url = "https://unsplash.com/images/animals/dog"
source_code = requests.get(url) #Gets source code from website
plain_text = source_code.text #only gets text from source code
soup = BeautifulSoup(plain_text) #Parses through the HTML of site
for div in (soup.find_all('div', class_= "_3oSvn IEpfq")):
img = div.find_all('img') #Finds all img in divs
for link in img: #Traverses all img
src = link.get("src") #Gets contents of src from img
img_name = random.randrange(1,500) #creates a unique name
full_name = data_dir + str(img_name) + ".jpg" #adds file type name
urllib.request.urlretrieve(src, full_name) #Fetch image of url and save into dir
【问题讨论】:
-
使用 Selenium WebDriver 执行动态加载元素的 JavaScript。
-
@Barmar 我之前尝试过这样做,但我不知道如何将它合并到我的代码中......有什么建议吗?
-
@Barmar 我认为即使使用 selenium 也会遇到一些问题,因为图像是在用户滚动时动态加载的
-
除了模拟导致它们的用户操作之外,没有自动方法可以查看动态加载的内容。
-
无法知道可能会加载哪些图像。相当于停机问题。
标签: javascript python html web-scraping beautifulsoup