从网站获取图像

时间:2012-04-29 09:48:07

标签: python html xml recipe calibre

我尝试为recipe改进calibre并将默认封面图片替换为当前报纸封面图片。

前进的方式与get_cover_urllink)有关。

有两个问题:

  1. 封面图片的网址每天都在变化。
  2. 我对python几乎一无所知。
  3. 我希望这样的解决方案(伪代码):

    OPEN URL "http://epaper.derstandarddigital.at/";
    coverElement = (SEARCH HTML-ELEMENT "<img>" WITH ID "imgPage2" AND CLASS "page");
    coverUrl = (GET HTML-ATTRIBUTE "src" FROM coverElement);
    RETURN coverUrl;
    

    有没有办法在python中实现这个目的*)(仅使用python标准库)?

    *)Caliber-Recipes似乎是python代码

    [编辑] 这是我朋友提供的解决方案:

    #!/usr/bin/env  python
    
    import urllib
    from time import strftime
    
    
    def get_cover_url(self):
        highResolution = True
    
        date    = strftime("%Y/%Y%m%d")
        # it is also possible for the past
        #date    = '2012/20120503'
    
        urlP1   = 'http://epaper.derstandarddigital.at/'
        urlP2   = 'data_ep/STAN/' + date
        urlP3   = '/V.B1/'
        urlP4   = 'paper.htm'
        urlHTML = urlP1 + urlP2 + urlP3 + urlP4
    
        htmlF  = urllib.urlopen(urlHTML)
        htmlC  = htmlF.read()
    
    
        # URL EXAMPLE: data_ep/STAN/2012/20120504/V.B1/pages/A3B6798F-2751-4D8D-A103-C5EF22F7ACBE.htm
        # consists of part2 + part3 + 'pages/' + code
        # 'pages/' has length 6, code has lenght 36
    
        index   = htmlC.find(urlP2) + len(urlP2 + urlP3) + 6 
        code    = htmlC[index:index + 36]
    
    
        # URL EXAMPLE HIGH RESOLUTION: http://epaper.derstandarddigital.at/data_ep/STAN/2012/20120504/pagejpg/A3B6798F-2751-4D8D-A103-C5EF22F7ACBE_b.png
        # URL EXAMPLE LOW RESOLUTION: http://epaper.derstandarddigital.at/data_ep/STAN/2012/20120504/pagejpg/2AB52F71-11C1-4859-9114-CDCD79BEFDCB.png
    
        urlPic  = urlP1 + urlP2 + '/pagejpg/' + code
    
        if highResolution:
            urlPic  = urlPic + '_b'
    
        urlPic  = urlPic + '.png'
    
        return urlPic
    
    
    
    if __name__ == '__main__':
        print get_cover_url(None)
    

1 个答案:

答案 0 :(得分:3)

您可以使用lxml库从HTML文档中提取元素。基本框架看起来像这样:

import urllib
import lxml.html

fd = urllib.urlopen('http://epaper.derstandarddigital.at/')
doc = lxml.html.parse(fd)
matches = doc.xpath('//img[@id="imgPage2]')
if matches:
  print matches[0].get('src')

...但是,您提供的网址实际上并不会产生包含任何<img>标记的文档。它几乎完全是一堆Javascript。