4 回答

TA貢獻1827條經驗 獲得超8個贊
要提取src
圖像的屬性,您需要為 引入WebDriverWait,visibility_of_element_located()
您可以使用以下任一 定位器策略:
使用CSS_SELECTOR:
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--headless')
options.add_argument('--window-size=1920,1080')
driver = webdriver.Chrome(options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get('https://www.sky.com/tv-guide/20200605/4101-1/107/Efe2-364')
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.o-layout__item div.c-bezel.programme-content__image>img"))).get_attribute("src"))
使用XPATH:
options = webdriver.ChromeOptions()
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--headless')
options.add_argument('--window-size=1920,1080')
driver = webdriver.Chrome(options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
driver.get('https://www.sky.com/tv-guide/20200605/4101-1/107/Efe2-364')
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='o-layout__item']//div[@class='c-bezel programme-content__image']/img"))).get_attribute("src"))
控制臺輸出:
https://images.metadata.sky.com/pd-image/251eeec2-acb3-4733-891b-60f10f2cc28c/16-9/640
注意:您必須添加以下導入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

TA貢獻1712條經驗 獲得超3個贊
你有正確的xpath,但不要使用絕對路徑,它很容易被改變。試試這個親戚xpath://div[@class="c-bezel programme-content__image"]//img。
為了實現你的意思,請.get_attribute("src")不要使用.text
driver.get('https://www.sky.com/tv-guide/20200605/4101-1/107/Efe2-364')
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, '//div[@class="c-bezel programme-content__image"]//img')))
print(element.get_attribute("src"))
driver.quit()
或者更好的方法,使用 css 選擇器。這應該更快:
element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, '.c-bezel.programme-content__image > img')))
參考:https ://selenium-python.readthedocs.io/locating-elements.html

TA貢獻1796條經驗 獲得超7個贊
您的 xpath 似乎是正確的。您無法定位,因為您忘記處理 cookie。自己試試吧。將驅動程序擱置幾秒鐘,然后單擊同意所有 cookie。然后你會看到你的元素。有多種方式來處理cookie。我能夠通過使用我自己的更干凈的 xpath 來找到 xpath。我從最近的父母那里訪問那個元素。

TA貢獻1802條經驗 獲得超5個贊
如果您在無頭模式下工作,通常增加窗口大小是個好主意。將此行添加到您的選項中:
chrome_options.add_argument('window-size=1920x1080')
添加回答
舉報