首页 > 解决方案 > 如何提取包含匹配字符串的字符串

问题描述

我的代码在下面,它提取所有元素

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/

标签: python

解决方案


条件表达式需要一个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'])

推荐阅读