【问题标题】:Download a captcha image without an extension下载没有扩展名的验证码图像
【发布时间】:2017-01-20 00:37:06
【问题描述】:
如何使用 PIL 或其他图像处理库下载this 验证码图像,我尝试了多种方法但无法下载图像。
from PIL import Image
import urllib2 as urllib
import io
fd = urllib.urlopen("https://notacarioca.rio.gov.br/senhaweb/CaptchaImage.aspx?guid=9759fc80-d385-480a-aa6e-8e00ef20be7b&s=1")
image_file = io.BytesIO(fd.read())
im = Image.open(image_file)
print im
【问题讨论】:
标签:
python
io
download
beautifulsoup
python-requests
【解决方案1】:
您尝试下载的图片没有静态网址。
链接工作:
相同的链接不再有效:
这意味着您不能使用静态 url 来引用图像(urllib.urlopen("https://notacarioca.rio.gov.br/senhaweb/CaptchaImage.aspx?guid=9759fc80-d385-480a-aa6e-8e00ef20be7b&s=1") 不起作用)。
这是我使用Requests 和BeautifulSoup 的解决方案:
import requests
from mimetypes import guess_extension
from bs4 import BeautifulSoup
from urllib.parse import urljoin
# from PIL import Image
# from io import BytesIO
s = requests.session()
r = s.get("https://notacarioca.rio.gov.br/senhaweb/login.aspx")
if r.status_code == 200:
soup = BeautifulSoup(r.content, "html.parser")
div = soup.find("div", attrs={"class": "captcha", "style": "color:Red;width:100%;"})
r = s.get(urljoin("https://notacarioca.rio.gov.br/senhaweb/", div.img["src"]))
if r.status_code == 200:
guess = guess_extension(r.headers['content-type'])
if guess:
with open("captcha" + guess, "wb") as f:
f.write(r.content)
# Image.open(BytesIO(r.content)).show()
【解决方案2】:
不确定现阶段是否需要这样做,因为最初的过去是几年前的事了,尽管如果其他人在类似问题上需要帮助,我会做出回应。经过几天的搜索,我终于让它工作了。 Theory 是 Selenium 4,你可以截图一个元素。
这是我在 Powershell 中的代码:
ForEach ($Img_Element in (Find-SeElement -Driver $browser -TagName img))
{
if ($Img_Element.GetAttribute('src') -notlike "*CaptchaImage.aspx*"){Continue}
$Screenshot = $Img_Element.GetScreenshot().AsBase64EncodedString
$bytes = [Convert]::FromBase64String($Screenshot)
[IO.File]::WriteAllBytes($File_CaptchaImg, $bytes)
Break
}
根据您的脚本语言,此视频也可能会有所帮助:https://www.youtube.com/watch?v=0pjzLMbtimk(如果您想跳转到@5:28)