Python - Beautifulsoup 到带有图片的 PDF(相对路径)

标签 python html pdf path beautifulsoup

我使用 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

最佳答案

这可能是答案的一半,但下面的代码可以帮助您将 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)

关于Python - Beautifulsoup 到带有图片的 PDF(相对路径),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33068747/

相关文章:

python - 有没有一种方法可以在不使用 Python API 的情况下执行 PyObject 的深层复制(例如通过 C、Rust 等)?

python - 替换numpy数组值python

Scipy径向基函数(scipy.interpolate.rbf)中的Python MemoryError

javascript - 转义用户生成的内容 - 这意味着什么?

javascript - 如何设置彼此相邻的图像列表

python - 如何使用 Python 从 PDF 中删除文本

python - 无法打开编解码器 'libopenh264' : Unspecified error

javascript - (JS) 使用 IF/Switch 语句更改 slider 值

ruby-on-rails - 邪恶中的混合取向.pdf

linux - 有没有办法用golang将PDF转换为jpeg?