python selenium下载图片_在Python中使用Selenium Webdriver下载图像

I am trying to download an image from a URL using Selenium Webdriver in Python. The site is protected by a login page, so can't just save the URL contents using requests. I am able to get text from the site after logging in, but I can't figure out how to save an image.

After I log in to the site, I can do browser.save_screenshot(filename + '.png') but that image is not the correct size as the original.

The code that I have now is this:

browser = webdriver.Chrome('../chromedriver')

browser.get('www.example.com/login')

# send username and password, click submit

browser.get('www.example.com/123')

html = browser.page_source

printData(html)

# this url is an image file

browser.get('www.example.com/get_photo.php?id=123')

browser.save_screenshot(filename + '.png')

Ideally I would like to replace the save_screenshot() with something like

with open(filename + '.jpeg', 'w') as img:

image.write(browser.download_current_image())

or even something like this, interacting with the popup menu

browser.right_click()

browser.down_arrow_key()

browser.return_key()

or simulating a keypress

browser.command_key()

browser.s_key()

This question gives the answers that I want, but not for Python. If there is a way to do any of the things suggested in that question (besides taking a screenshot) in Python, that would be a great solution.

解决方案

Here is what I used to download an image from a URL behind a login page by logging in using Selenium Webdriver and then passing the cookies to requests to save the image:

headers = {

"User-Agent":

"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"

}

s = requests.session()

s.headers.update(headers)

for cookie in browser.get_cookies():

c = {cookie['name']: cookie['value']}

s.cookies.update(c)

r = s.get(imgurl, allow_redirects=True)

open(filename + '.jpeg', 'wb').write(r.content)

Thanks to AldoSuwandi for showing me how to do this in this post. I also used this site to help me figure out how to download an image using requests.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值