【发布时间】:2018-11-08 18:29:14
【问题描述】:
我有这个脚本可以从 Instagram 下载图片。我遇到的唯一问题是,当 Selenium 开始向下滚动到网页底部时,BeautifulSoup 在循环请求后开始抓取相同的 img src 链接。
虽然它会继续向下滚动并下载图片,但在完成之后,我最终会有 2 或 3 个重复。所以我的问题是有没有办法防止这种重复发生?
import requests
from bs4 import BeautifulSoup
import selenium.webdriver as webdriver
url = ('https://www.instagram.com/kitties')
driver = webdriver.Firefox()
driver.get(url)
scroll_delay = 0.5
last_height = driver.execute_script("return document.body.scrollHeight")
counter = 0
print('[+] Downloading:\n')
def screens(get_name):
with open("/home/cha0zz/Desktop/photos/img_{}.jpg".format(get_name), 'wb') as f:
r = requests.get(img_url)
f.write(r.content)
while True:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(scroll_delay)
new_height = driver.execute_script("return document.body.scrollHeight")
soup = BeautifulSoup(driver.page_source, 'lxml')
imgs = soup.find_all('img', class_='_2di5p')
for img in imgs:
img_url = img["src"]
print('=> [+] img_{}'.format(counter))
screens(counter)
counter = counter + 1
if new_height == last_height:
break
last_height = new_height
更新:
所以我把这部分代码放在while True之外,让selenium首先加载整个页面,希望bs4能刮掉所有的图像。它只工作到 30 号,然后停止。
soup = BeautifulSoup(driver.page_source, 'lxml')
imgs = soup.find_all('img', class_='_2di5p')
for img in imgs:
#tn = datetime.now().strftime('%H:%M:%S')
img_url = img["src"]
print('=> [+] img_{}'.format(counter))
screens(counter)
counter = counter + 1
【问题讨论】:
标签: python selenium beautifulsoup