python - 使用正则表达式从给定的链接列表中提取 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"$)"""
解决方案
每个人都会告诉你使用正则表达式处理 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'])
简单明了,不是吗?
推荐阅读
- c# - 登录失败后将用户名传回 MVC 视图/文本框
- python - 使用 Python Selenium 访问下拉元素
- bash - 从服务器重新生成脚本获取服务器崩溃的输出
- pine-script - Pine Scripts plotshapes偏移问题
- excel - 在 Excel 工作表中组合相应的数据
- angular - 你将如何返回 Observable
从一个函数 - rcpp - Rcpp:获取临时对象类型代理的地址,从 CharacterVector 中获取子向量
- sql - 迄今为止的标准 SQL 字符串
- javascript - 如果类列表包含多个特定类
- clojure - 从 src 目录提供图像文件 - 404 错误