簡體   English   中英

使用 Selenium (Python) 提取圖像

[英]Extract images with Selenium (Python)

我正在學習網絡抓取,現在我想知道是否可以從網站中提取圖像並將其放入 excel 文件中?

我在這個網站工作: https : //www.browniespain.com/es/novedades/

這里是我的代碼:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import os
import openpyxl
from openpyxl import Workbook
import time


browser=webdriver.Safari()
browser.get("https://www.browniespain.com/es/novedades/")

primera = "//*[@id='center_column']/div[6]/div["
segunda ="]/div/div[2]/div[1]/h5/a"

productos = len(browser.find_elements_by_xpath('//*. [@id="center_column"]/div[6]/div'))

print(productos)

for n in range(1,productos+1):
  direccion = primera+str(n)+segunda
  nombre_producto = browser.find_element_by_xpath(direccion).text
  file_name = 'NovedadesBrownie.xlsx'

  if(os.path.exists(file_name)):
    workbook = openpyxl.load_workbook(file_name)
    worksheet = workbook.get_sheet_by_name('Sheet')
  else:
    workbook = Workbook()
    worksheet = workbook.active
  worksheet.cell(row=n,column=1).value = nombre_producto
  workbook.save(file_name)



  print(nombre_producto)

  primera = "//*[@id='center_column']/div[6]/div["
  segunda ="]/div/div[2]/div[1]/div[2]/span"

  productos = len(browser.find_elements_by_xpath('//*[@id="center_column"]/div[6]/div'))

  print(productos)

  for n in range(1,productos+1):
    direccion = primera+str(n)+segunda
    precio_producto = browser.find_element_by_xpath(direccion).text

    if(os.path.exists(file_name)):
      workbook = openpyxl.load_workbook(file_name)
      worksheet = workbook.get_sheet_by_name('Sheet')
    else:
      workbook = Workbook()
      worksheet = workbook.active
    worksheet.cell(row=n,column=2).value = precio_producto
    workbook.save(file_name)



    print(precio_producto)

    browser.close()

您知道提取圖像並將其放入該 Excel 文件的任何想法嗎?

您的 XPath 語法不正確。 像這樣嘗試:

browser.find_elements_by_xpath('//*[@id="center_column"]/div[6]/div')

其余代碼似乎按預期工作。

但是,要獲取圖像,您需要使用這樣的 XPath:

//div/a/img[contains(@class,'imgcat')]

然后使用 get_attributethe 檢索 src URL:

for i in  elements:
    image = i.find_elements_by_xpath("//div/a/img[contains(@class,'imgcat')]")
    img_src = image.get_attribute("src")

接下來,我建議將文件下載到本地光盤

import urllib.request
urllib.request.urlretrieve("http://www.example.com/news/media/test.jpg", "local-filename.jpg")

並將它們添加到您的工作表中。

import openpyxl

wb = openpyxl.Workbook()
ws = wb.worksheets[0]
img = openpyxl.drawing.Image('local-filename.jpg')
img.anchor(ws.cell('A1'))
ws.add_image(img)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM