如何使用selenium下载图像

2024-10-01 04:45:05 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有一个页面上的图片,必须下载,然后用于导入到另一个网站

whis是站点的外观

enter image description here

我想使用xpath下载它,xpath是//*[@id="word-img"]/img

图片的代码如下所示

    <div id="word-img" style="width: 600px; height: 200px; margin-bottom: 20px; background: white;"><img src="https://10fastfingers.com/anticheat/generate_word_picture?rand=8644839612" alt=""></div>

<img src="https://10fastfingers.com/anticheat/generate_word_picture?rand=8644839612" alt="">

Tags: httpsdivsrccomidimg图片页面
1条回答
网友
1楼 · 发布于 2024-10-01 04:45:05

有几种方法可以做到这一点。
1.

import urllib

# get the image source
img = driver.find_element_by_xpath('//*[@id="word-img"]/img')
src = img.get_attribute('src')

# download the image
urllib.urlretrieve(src, "my_image.png")
with open('my_picture.png', 'wb') as file:
    file.write(driver.find_element_by_xpath('//*[@id="word-img"]/img').screenshot_as_png)

相关问题 更多 >