为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕姐4208626 2024-01-15 21:38:52
我的代码如下,提取所有元素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/
查看完整描述

2 回答

?
慕村9548890

TA贡献1884条经验 获得超4个赞

条件表达式需要一个else子句来指定当条件为 false 时表达式应返回的内容。


但在这种情况下您不想打印任何内容。因此,请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'])


查看完整回答
反对 回复 2024-01-15
?
30秒到达战场

TA贡献1828条经验 获得超6个赞

您正在链接中搜索“about”,而“about”一词似乎在链接['href']中找到。因此尝试如下更新 if 条件。

print(link['href'] if 'about' in link['href'] else '')


查看完整回答
反对 回复 2024-01-15
  • 2 回答
  • 0 关注
  • 32 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信