【问题标题】:Is there a more broad way to get the src in a webelement through selenium?有没有更广泛的方法可以通过 selenium 在 webelement 中获取 src?
【发布时间】:2020-01-04 23:10:51
【问题描述】:

我之前已经从其他 webelements 中提取了“src”,但是这个似乎让我无法理解。我正在尝试获取此网页上所有图像的所有链接。但是,即使 web 元素被 css 选择器突出显示,当我尝试通过 get_attribute('src') 抓取它时,它也不会返回链接。如果我使用 Xpath 或 Css Selector 获得特定的图像,我可以实现抓取一张图像,但我想一次抓取它们的所有(7 个 url)并将它们扔到一个列表中。

有什么建议吗?

这是我的代码:


from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.action_chains import ActionChains
from json import dumps, loads, JSONEncoder, JSONDecoder

import re
import json
import timeit
import time

start = timeit.default_timer()

driver = webdriver.Chrome()

wait = WebDriverWait(driver, 5)



def ImageFind():
    driver.get('https://shop.freedommobile.ca/devices/Apple/iPhone_11?sku=190199220546&planSku=Freedom%205GB')


    phoneImage = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.slide')))
    imageLink = phoneImage[0].get_attribute('src') #test for grabbing url for just one webelement

    print(len(phoneImage)) #check to make sure I have the right amount of elements being selected
    print(phoneImage) 
    print(imageLink)

    return imageLink


ImageFind()


【问题讨论】:

    标签: python selenium web-scraping


    【解决方案1】:

    你使用了错误的选择器,.slide 是一个 li 元素并且没有 src 属性。要获取图像,请使用.slide img,如下例所示:

    images = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.slide img')))
    for image in images:
        print(image.get_attribute('src'))
    

    你的方法:

    def image_find():
        driver.get('https://shop.freedommobile.ca/devices/Apple/iPhone_11?sku=190199220546&planSku=Freedom%205GB')
    
        images = [image.get_attribute('src') for image in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '.slide img')))]
        return images
    

    【讨论】:

      猜你喜欢
      • 2015-10-18
      • 2021-01-13
      • 2019-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-12
      • 1970-01-01
      相关资源
      最近更新 更多