【问题标题】:How to get image URI in Selenium?如何在 Selenium 中获取图像 URI?
【发布时间】:2014-07-22 12:35:53
【问题描述】:

我使用了question 的第一个答案以使其适应我的需要:自动将给定 URL 的图片保存在我的笔记本电脑上。

我的问题是如何获取网页上存在的每个图像的 URI 以正确完成我的代码:

 import selenium
    class TestFirefox:
        def testFirefox(self):
            self.driver=webdriver.Firefox()
            # There are 2 pictures on google.com, I want to download them
            self.driver.get("http://www.google.com")
            self.l=[] # List to store URI to my images
            self.r=self.driver.find_element_by_tag_name('img')
            # I did print(self.r) but it does not reflect the URI of 
            # the image: which is what I want.

            # What can I do to retrieve the URIs and run this:
            self.l.append(self.image_uri)
            for uri_to_img in self.l:
               self.driver.get(uri_to_img)

               # I want to download the images, but I am not sure 
               # if this is the good way to proceed since my list's content
               # may not be correct for the moment 
               self.driver.save_screenshot(uri_to_image)
               driver.close()
    if __name__=='__main__':
        TF=TestFirefox()
        TF.testFirefox()

【问题讨论】:

    标签: firefox selenium python-3.x selenium-webdriver


    【解决方案1】:

    您需要获取给定图像的 src 属性以确定它的名称和(可能)地址 - 请记住,src 也可以是相对 URI。

    for img in self.l:
        url = img.get_attribute("src")
    

    要下载图像,您应该尝试简单的 HTTP 客户端,例如 urllib

    import urllib.request  
    
    urllib.request.urlretrieve(url, "image.png")
    

    【讨论】:

    • 我使用的是 Python-3.4,它说 urllib 没有名为 urlretrieve 的模块。哪个可以从这个列表中工作:docs.python.org/3.3/library/urllib.html?我使用了request,但它说它不是可调用对象
    • 我已经编辑了我的答案,这应该可以。另请注意,此遗留代码是从 Python 2 移植的,因此为了将来的兼容性,请使用类似 stackoverflow.com/questions/15846017/…
    • 我没有对你投反对票!相信我不是我!我可以在这里给你我的密码,你会检查自己我没有投反对票!!!!别人做了,不是我
    • 我相信你 :-) 但如果它对你有帮助,你可以投票或接受答案。
    • 是的,你在我心里,我会在不到 3 小时内测试你给我的解决方案(我现在正在编码其他东西),然后我会看到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 2011-06-21
    • 2021-07-02
    • 2018-06-06
    相关资源
    最近更新 更多