【问题标题】:Images download with BeautifulSoup使用 BeautifulSoup 下载图像
【发布时间】:2017-02-09 09:40:35
【问题描述】:

我正在使用 BeautifulSoup 来提取适用于普通页面的图片。 现在我想从这样的网页中提取 Chromebook 的图片

https://twitter.com/banprada/statuses/829102430017187841

该页面显然包含指向带有该图像的另一个页面的链接。这是我从提到的链接下载图片的代码,但我只获取发布链接的人的图片。

import urllib.request
import os
from bs4 import BeautifulSoup

URL = "http://twitter.com/banprada/statuses/829102430017187841"
list_dir="D:\\"
default_dir = os.path.join(list_dir,"Pictures_neu")
opener = urllib.request.build_opener()
urllib.request.install_opener(opener)
soup = BeautifulSoup(urllib.request.urlopen(URL).read())
imgs = soup.findAll("img",{"alt":True, "src":True})
for img in imgs:
   img_url = img["src"]
   filename = os.path.join(default_dir, img_url.split("/")[-1])
   img_data = opener.open(img_url)
   f = open(filename,"wb")
   f.write(img_data.read())
   f.close()

有机会以某种方式下载图像吗?

非常感谢和问候, 安迪

【问题讨论】:

  • 页面有JS在你用urllib获取网页时没有渲染
  • 尝试使用 JS 渲染器库,如 here 中提到的dryscrape
  • 所需图像位于 iframe 内,初始页面源中不存在该图像。您可以在Python + selenium 获得解决方案吗?
  • 感谢提示。 Python + selenium 可能是一个解决方案(如果有一个可行的解决方案会很棒)

标签: python beautifulsoup


【解决方案1】:

这就是使用Selenium + requests 获得仅提及图像的方法

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import requests

link = 'https://twitter.com/banprada/statuses/829102430017187841'
driver = webdriver.PhantomJS()
driver.get(link)
wait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe[starts-with(@id, 'xdm_default')]")))
image_src = driver.find_element_by_tag_name('img').get_attribute('src')
response = requests.get(image_src).content
with open('C:\\Users\\You\\Desktop\\Image.jpeg', 'wb') as f:
    f.write(response)

如果您想从页面上的all iframe 中获取所有图像(不包括可以通过代码获取的初始页面源中的图像):

from selenium import webdriver
from selenium.common.exceptions import WebDriverException
import requests
import time

link = 'https://twitter.com/banprada/statuses/829102430017187841'
driver = webdriver.Chrome()
driver.get(link)
time.sleep(5) # To wait until all iframes completely rendered. Might be increased
iframe_counter = 0
while True:
    try:
        driver.switch_to_frame(iframe_counter)
        pictures = driver.find_elements_by_xpath('//img[@src and @alt]')
        if len(pictures) > 0:
            for pic in pictures:
                response = requests.get(pic.get_attribute('src')).content
                with open('C:\\Users\\You\\Desktop\\Images\\%s.jpeg' % (str(iframe_counter) + str(pictures.index(pic))), 'wb') as f:
                    f.write(response)
        driver.switch_to_default_content()
        iframe_counter += 1
    except WebDriverException:
        break

注意,您可以使用any webdriver

【讨论】:

    猜你喜欢
    • 2021-03-31
    • 2020-08-02
    • 2016-09-06
    • 2019-07-24
    • 2022-11-06
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 2013-09-01
    相关资源
    最近更新 更多