如何从链接获取图像?

时间:2016-02-28 05:41:14

标签: python selenium selenium-webdriver beautifulsoup bs4

当我尝试通过此代码访问图片代码时,我会得到以下输出。

url = 'https://paytm.com/shop/p/pepe-jeans-blue-slim-fit-t-shirts-APPPEPE-JEANS-BSETU2010438B648267'

def soup_maker(url):
    r = requests.get(url)
    markup = r.content
    soup = bs(markup, "html.parser")
    return soup

def get_images(url):
    soup = soup_maker(url)
    divs = soup.find_all('div', {'class': 'fixed-height'})
    print(divs)
    images = soup.find_all('img')
    print(images)

输出

[]
[<img alt="{{::product.text}}" ng-src="{{::product.image_url}}"/>, 
 <img alt="{{item.title}}" ng-src='{{cart.imgResized(item.image_url,"50x50") }}'/>, 
 <img ng-src="{{pixelSource}}"/>]

但是当我通过Inspect Element看到它时。我不知道如何保存这些图像。

更新

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

def soup_maker(url):
    driver = webdriver.Chrome()
    driver.get(url)
    try:
        element = WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.CLASS_NAME, "fixed-height"))
        )
        markup = driver.page_source
        soup = bs(markup, "html.parser")
        return soup
    finally:
        driver.quit()
    driver.close()

上面为我工作。

1 个答案:

答案 0 :(得分:2)

这看起来像一个带有已定义绑定的AngularJS模板,这意味着该网站需要一个真实的浏览器,并且需要渲染一个javascript引擎。让我们保持解析部分不变,但不是requests,而是通过selenium

from selenium import webdriver

def soup_maker(url):
    driver = webdriver.Firefox()  # could also be Chrome(), PhantomJS() or other
    driver.get(url)

    # you might also need an Explicit Wait here to wait for the page to load
    # see http://selenium-python.readthedocs.org/waits.html#explicit-waits

    markup = driver.page_source
    driver.close()
    soup = bs(markup, "html.parser")
    return soup