【问题标题】:Download background Image with CSS selector - Selenium Python使用 CSS 选择器下载背景图片 - Selenium Python
【发布时间】:2020-07-24 08:52:50
【问题描述】:

我正在尝试使用 Python 和 Selenium 提取 website page 上的所有可用图片

为此,我使用 CSS 选择器,代码如下:

try :
    Pictures = self.browser.find_elements_by_css_selector('background-image')
except :
    Pictures = None

for picture in Pictures :
    print(picture.get_attribute("textContent"))

但是,什么都没有发生:没有消息错误,没有空白......什么都没有。

我的最终目标是能够下载这些图片;我该怎么办?

编辑 1:

【问题讨论】:

    标签: python css image selenium web-scraping


    【解决方案1】:

    尝试以下操作以从该页面获取图像。原来它们在页面源代码中可用,因此您不需要使用 selenium 来获取图像。您可以使用比 selenium 快得多的 requests 模块。鉴于这是你可以去的:

    import re
    import requests
    from bs4 import BeautifulSoup
    
    link = "https://www.sezane.com/fr/e-shop/collection-printemps-robes-robes-courtes"
    
    res = requests.get(link)
    soup = BeautifulSoup(res.text,"lxml")
    for item in soup.select("[id='cms_sortable'] .free-product__img"):
        match_image = re.search(r"url\('(.*?)'",item.get("style"))
        if match_image:
            print(match_image.group(1))
    

    输出如下:

    https://media.sezane.com/image/upload/q_auto:best/v1586276035/website/cms/product/imh92y33wziscjtz1mta.jpg
    https://media.sezane.com/image/upload/q_auto:best/v1585924567/website/cms/product/c7umxdbyyqocwc5gzghy.jpg
    https://media.sezane.com/image/upload/q_auto:best/v1585924561/website/cms/product/jfdjdxqo5ek3oeziggxc.jpg
    https://media.sezane.com/image/upload/q_auto:best/v1585931708/website/cms/product/qhmxfoo95ftlbzsiplid.jpg
    https://media.sezane.com/image/upload/q_auto:best/v1585907671/website/cms/product/ng7vbbd39cnooqzqgzgt.jpg
    

    【讨论】:

    • 我会检查请你解释一下你是如何选择使用 selenium 或 bs4 的?
    • Selenium 是浏览器模拟器,bs4 是 HTML 解析器。我不明白你在两者之间选择是什么意思。
    • 工作得很好,谢谢。你能评论一下你的代码循环吗?
    【解决方案2】:

    请尝试以下解决方案,在您的代码中 css 选择器不正确 ::

     driver.maximize_window()
     driver.get('https://www.sezane.com/fr/e-shop/collection-printemps-robes-robes-courtes')   
     elements = WebDriverWait(driver, 15).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[contains(@id,'_divVisualPrimary')]")))
    
    for element in elements:
       element=element.value_of_css_property("background-image")
       print(re.split('[()]',element)[1])
    

    注意:请在您的解决方案中添加以下导入

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

    【讨论】:

    • “免费产品链接”是详细页面的链接,不是图片的链接?
    • 您能否详细说明,因为使用 css 选择器的页面上没有背景图像
    • @AlexDana 请找到可行的解决方案,一旦您确认您是否愿意接受答案并从您的最后点击投票按钮。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    相关资源
    最近更新 更多