首页 > 解决方案 > 使用正则表达式从给定的链接列表中提取 pdf 链接

问题描述

我有一个存储为 LIST 的链接列表。但我只需要提取 PDF 链接。

    links = [ '<a class="tablebluelink" href="https://www.samplewebsite.com/xml-data/abcdef/higjkl/Thisisthe-required-document-b4df-16t9g8p93808.pdf" target="_blank"><img alt="Download PDF" border="0" src="../Include/images/pdf.png"/></a>', '<a class="tablebluelink" href="https://www.samplewebsite.com/xml-data/abcdef/higjkl/Thisisthe-required-document-link-4ea4-8f1c-dd36a1f55d6f.pdf" target="_blank"><img alt="Download PDF" border="0" src="../Include/images/pdf.png"/></a>']

所以我只需要提取从'https'开始并以pdf结尾的链接,如下所示

    https://www.samplewebsite.com/xml-data/abcdef/higjkl/Thisisthe-required-document-b4df-16t9g8p93808.pdf

并将此链接存储在列表中。变量“链接”中有许多 pdf 链接。需要将所有 pdf 链接存储在名为 'pdf_links' 的变量中

谁能建议我用正则表达式来提取这个 pdf 链接?我使用了下面的正则表达式,但它不起作用。

    pdf_regex = r""" (^<a\sclass="tablebluelink"\shref="(.)+.pdf"$)"""

标签: pythonregexpython-3.xpdf

解决方案


每个人都会告诉你使用正则表达式处理 HTML 是错误的。无论如何,我不想向您展示如何以这种方式完成它,我想向您展示使用库解析 HTML 实际上是多么容易,例如经常推荐的BeautifulSoup 4 。

为了使其简单且接近您的示例代码,我只是将您的输入列表展平。通常,您会将原始 HTML 直接提供给解析器(例如,请参见此处)。

from bs4 import BeautifulSoup
links = [ '<a class="tablebluelink" href="https://www.samplewebsite.com/xml-data/abcdef/higjkl/Thisisthe-required-document-b4df-16t9g8p93808.pdf" target="_blank"><img alt="Download PDF" border="0" src="../Include/images/pdf.png"/></a>', '<a class="tablebluelink" href="https://www.samplewebsite.com/xml-data/abcdef/higjkl/Thisisthe-required-document-link-4ea4-8f1c-dd36a1f55d6f.pdf" target="_blank"><img alt="Download PDF" border="0" src="../Include/images/pdf.png"/></a>']

soup = BeautifulSoup(''.join(links), 'lxml')
for link in soup.find_all('a', href=True):
    if link['href'].lower().endswith(".pdf"):
        print(link['href'])

简单明了,不是吗?


推荐阅读