请考虑以下任务:


打开一个给定的URL
在网址中找到第一个图片标签
将其替换为本地驱动器中的映像
将结果网页另存为png


我想使用Python脚本自动执行此任务,但我不确定最佳方法。

我一直在使用硒将URL转换为屏幕截图,但是我不确定如何介绍有关修改第一个图像标签以加载本地文件的部分。

最佳答案

您可以使用execute_script替换图像,如下所示:

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

browser = webdriver.Firefox()
url = 'https://www.aircanada.com/en/'
browser.get(url)

my_image = browser.find_element_by_xpath('//*[@id="pagePromoBanner-wrapper"]/div/a/img')

# or
# my_image = browser.find_element_by_xpath('any XPath')

link_to_new_image = "https://images.pexels.com/photos/67636/rose-blue-flower-rose-blooms-67636.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
# if you are using python 3.6 and up:
browser.execute_script(f"arguments[0].src = '{link_to_new_image}'", my_image )
# else:
# browser.execute_script("arguments[0].src = '"+link_to_new_image+"'", my_image )


希望这对您有所帮助!

关于python - 自动在网络图像中替换徽标,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54869287/

10-12 21:46