python - 如何提取包含匹配字符串的字符串
问题描述
我的代码在下面,它提取所有元素
for link in soup.find_all('a', href=True):
print(link['href'])
输出
https://www.example.com/author/1/
https://www.example.com/about/2/
https://www.example.com/author/3/
(链接['href'])的类型
<cls str>
<cls str>
<cls str>
我需要提取包含“关于”的网址
我试过print(link['href'] if 'about' in link)
哪个抛出的错误
我的预期
https://www.example.com/about/2/
解决方案
条件表达式需要一个else
子句来指定条件为假时表达式应返回的内容。
但是在这种情况下你不想打印任何东西。因此,请在通话周围使用if
声明。print()
for link in soup.find_all('a', href=True):
if 'about' in link['href']:
print(link['href'])
您也可以在soup.find_all()
通话中进行匹配。
for link in soup.find_all('a', href=re.compile(r'about')):
print(link['href'])
推荐阅读
- ios - 清除 WKWebView 历史记录,避免在浏览历史记录中来回走动
- c# - 如何返回 lIEnumerable 列表
- kubernetes - 新应用金丝雀发布策略
- python - 在 Jupyter 笔记本中导入包时出错
- c - C语言中的realloc是线性的吗?
- c++ - 为什么即使在调用参数化构造函数时也会调用默认构造函数?
- sql - 在 SQL Developer 中插入 TIMESTAMP 值
- r - 如何遍历环境中的数据框对象
- python - 请解释 Python 字典的这种行为
- javascript - 如何强制 Django 使用 CDN 中的 select2 而不是本地管理员版本?