Python:保存页面的动态图像

时间:2014-08-21 18:47:10

标签: python python-2.7

我需要以编程方式加载HTML页面的内容,该页面的主体中包含动态图像。然后我想下载并保存此图像,因为它显示该页面加载的时间。

HTML中的图像示例:

<img src="image.php">

问题是我无法在http://example.com/image.php获取PHP脚本的内容,因为它只会生成并返回另一个图像,而不是原始页面中生成的相同图像。

那么,如何保存该页面中生成的图像?我知道我无法使用webbrowser,因为它会打开一个实际的浏览器窗口。我考虑使用zope.testbrowsermechanize,但是找不到有关如何操作的任何信息。

你们能帮助我吗?

2 个答案:

答案 0 :(得分:2)

使用mechanize,cookielib和urllib解决。

首先,设置导入和无头浏览器处理程序:

# Mechanize headless
import mechanize
import cookielib
import urllib
# Browser
br = mechanize.Browser()
# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
# Want debugging messages?
#br.set_debug_http(True)
#br.set_debug_redirects(True)
#br.set_debug_responses(True)

添加&#34;人类&#34;标题,所以你不会被误认为是机器人...

# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

现在你可以正常地#34;导航&#34;使用open方法。动态图像也可以加载open。只需遵循页面/文件层次结构序列,mechanize / cookielib将为您处理标题...

r = br.open('http://www.example.com/html-page-with-dynamic-image-embedded.html')

# Check if HTML content returned ok
if br.response().info()['Content-Type'] == 'text/html; charset=iso-8859-1':
    # Now that the main page is loaded you can open the dynamic image
    r = br.open('http://www.example.com/images/image.php')

    # From here you just treat the image as you wish
    png = r.read()
    f = open('image-new-name.png', 'wb')
    f.write(png)
    f.close()  

如果您需要像这样发送URL GET数据

,则使用Urllib
data = {'varName1': var1, 'varName2': var2, ...}
data = urllib.urlencode(data)
r = br.open('http://www.example.com/html-page-with-dynamic-image-embedded.html', data)

答案 1 :(得分:0)

我还是初学者 - 但我在类似情况下使用BeautifulSoup来从网站下载图片。

使用此库获取图像应该很容易。