如何提取包含匹配字符串的字符串

我的代码如下,提取所有元素


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/

(link['href']) 的类型


<cls str>

<cls str>

<cls str>

我需要提取包含“about”的网址


我尝试用print(link['href'] if 'about' in link)哪个抛出错误


我的预期结果


https://www.example.com/about/2/


慕姐4208626
浏览 39回答 2
2回答

慕村9548890

条件表达式需要一个else子句来指定当条件为 false 时表达式应返回的内容。但在这种情况下您不想打印任何内容。因此,请if在print()调用周围使用声明。for link in soup.find_all('a', href=True):&nbsp; &nbsp; if 'about' in link['href']:&nbsp; &nbsp; &nbsp; &nbsp; print(link['href'])您也可以在通话中进行匹配soup.find_all()。for link in soup.find_all('a', href=re.compile(r'about')):&nbsp; &nbsp; print(link['href'])

30秒到达战场

您正在链接中搜索“about”,而“about”一词似乎在链接['href']中找到。因此尝试如下更新 if 条件。print(link['href']&nbsp;if&nbsp;'about'&nbsp;in&nbsp;link['href']&nbsp;else&nbsp;'')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python