【问题标题】:Python - Beautifulsoup to PDF with picture (relative paths)Python - Beautifulsoup 到 PDF 与图片(相对路径)
【发布时间】:2016-01-09 04:50:18
【问题描述】:

我使用 mechanize 浏览网站。在此之后,我使用 beautifulsoup 来操作网页的内容(转换为 unicode,删除一些行)。现在我想从使用 Beautifulsoup 获得的 html 源创建 PDF 文件。使用 pdfkit,它适用于文本。但现在我还想用 html 代码中的图片创建 pdf。通过使用相对路径“../../”等指定 url(也适用于图片)。

如何更改所有 url 以考虑绝对路径以及如何获取 pdf 文件中的图片?路径的变化是否足以获取图片?

解决方案:(基于 dudu1791 提案)

#changement liens vers images
def ChangeLinkIMG(soup,baseurl):
    #parcours des images
    for imgLK in soup.findAll('img'):    
        #chemin relatif image
        try:
            relaIMG=imgLK['src'] 
            #creation lien absolu
            absoIMG=urljoin(baseurl,relaIMG)
            imgLK['src']=absoIMG
            print absoIMG
        except:
            pass
    return soup

【问题讨论】:

    标签: python html pdf path beautifulsoup


    【解决方案1】:

    它可能是答案的一半,但下面的代码可以帮助您转换 url 以考虑绝对路径。我就是这样做的。

    def parse_all_links(self, soup):            
            for link in soup.find_all('a'):                
                if(link.get('href')):
                    href = link.get('href')
                    if href.startswith('http') or href.startswith('https'):
                        print(href)                        
                    elif href =='#':
                        #print('No link present')
                        pass
                    elif href =='/':
                        pass
                    else:
                        href = baseurl + href
                        print(href)
    

    【讨论】:

    • 谢谢!我修改了你处理图片的建议。我在帖子中写了我的函数。
    猜你喜欢
    • 2021-05-14
    • 2018-06-05
    • 2018-03-23
    • 1970-01-01
    • 2012-01-10
    • 2012-01-11
    • 2018-08-20
    • 2018-06-09
    • 1970-01-01
    相关资源
    最近更新 更多