【问题标题】:Using python selenium webdriver to upload an image to google image search使用 python selenium webdriver 上传图片到谷歌图片搜索
【发布时间】:2020-05-11 23:38:02
【问题描述】:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import sys, os
from time import sleep

class searcher():
    """
    Google reverse image search bot
    Dependincies:
        - Selenium
        - Chrome Webdriver
    """

    def __init__(self, headless=False):
        os.chdir('../images_backend')
        self.image_dir = os.getcwd()
        print(self.image_dir)

        platform = ""
        end = ""

        if 'linux' in sys.platform:
            platform = 'linux'
        elif 'win' in sys.platform and 'dar' not in sys.platform:
            end = '.exe'
            platform = 'win'
        elif 'dar' in sys.platform:
            platform = 'mac'


        options = webdriver.ChromeOptions()
        if headless:
            options.add_argument('--window-size=1920,1080')
            options.add_argument('headless')
            options.add_argument('--start-maximized')
        self.driver = webdriver.Chrome('../webdriver/' + platform + '/chromedriver' + end, options=options)


    def __del__(self):
        self.driver.close()

    def __open_image_dialog(self):
        self.driver.get("https://www.google.com/imghp?hl=EN")
        cam_button = self.driver.find_elements_by_xpath("//div[@aria-label=\"Search by image\" and @role=\"button\"]")[0]
        cam_button.click()
        upload_image = self.driver.find_elements_by_xpath("//div[@class=\"qbtbha sl\"]")[0]
        upload_image.click()
        self.upload_dialog = self.driver.find_elements_by_xpath("//input[@id=\"qbfile\" and @name=\"encoded_image\"]")[0]


    def open_shopping_section(self):
        shop_button = self.driver.find_element_by_xpath(".//a[text()=\"Shopping\" and @class=\"q qs\"]")
        shop_button.click()


    def select_lo2hi(self):
        b1 = self.driver.find_element_by_xpath(".//span[@class=\"Yf5aUd\"]")
        b1.click()
        sleep(1)
        self.driver.find_element_by_xpath(".//g-menu-item[.//div[text()=\"PRICE – LOW TO HIGH\"]]").click()


    def text(self):
        return self.driver.text

    **def upload_image(self, path):**
        try:
            self.upload_dialog
        except:
            self.__open_image_dialog()
        self.upload_dialog.send_keys(self.image_dir + "/" + path)

    def find_products(self):
        q = []
        products = self.driver.find_elements_by_xpath('//div[@class=\"uMfazd\"]')
        for prod in products:
            for i in range(3):
                link = prod.find_elements_by_xpath("//a[@class=\"EI11Pd p7n7Ze\" and @data-what=\"1\"]")[i]
                q += [link.get_attribute('href')]
        return list(set(q))

s = searcher(headless=False)
s.upload_image('teddybear.jpg')


print('opening shopping section')

s.open_shopping_section()

sleep(3)

print('select lo2hi')

s.select_lo2hi()


print(s.find_products())

s.driver.save_screenshot('screened.png')

del s

这是我现在尝试调试的代码。它使用带有 python 3.8 的 selenium chrome webdriver 获取图像并通过自动反向谷歌图像搜索运行它。

它给了我一个错误细节:

backend\search_api.py", line 68, in upload_image self.upload_dialog AttributeError: 'searcher' object has no attribute 'upload_dialog'

我对使用 python 和 selenium 比较陌生,所以任何指针或建议将不胜感激 :)

谢谢

【问题讨论】:

  • 如果你没有死心塌地使用 selenium,有一个alternative

标签: python selenium selenium-webdriver google-image-search


【解决方案1】:

编辑:您似乎已经让它部分工作了。由于我的评分很低,我无法发表评论,所以我在代码解决方案下方提出一个问题。

这是一个通过 Google 进行 Selenium 反向图像搜索的工作示例:

from selenium import webdriver
import os
import time

# Using Chrome to access web
driver = webdriver.Chrome(executable_path=os.path.abspath("chromedriver"))

try:
    # Open the website
    driver.get('https://images.google.com/')

    # Find cam button
    cam_button = driver.find_elements_by_xpath("//div[@aria-label=\"Search by image\" and @role=\"button\"]")[0]
    cam_button.click()

    # Find upload tab
    upload_tab = driver.find_elements_by_xpath("//*[contains(text(), 'Upload an image')]")[0]
    upload_tab.click()

    # Find image input
    upload_btn = driver.find_element_by_name('encoded_image')
    upload_btn.send_keys(os.getcwd()+"/image.png")

    time.sleep(10)

except Exception as e:
    print(e)

driver.quit()

另外,我想问一下,你为什么不先运行open_image_dialog,然后再运行upload_dialog

def upload_image(self, path):
        self.__open_image_dialog()
        self.upload_dialog.send_keys(self.image_dir + "/" + path)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多