如何从BeautifulSoup提取的href中筛选包含指定字符串的目标URL
报错原因
原代码的判断逻辑存在偏差:循环中的link是BeautifulSoup生成的<a>标签元素对象,并非存储URL的字符串,原代码直接执行'about' in link,本质是拿元素对象做字符串包含匹配,自然会触发运行错误。
修正实现
可根据需求选择两种适配写法:
- 适配现有循环流程的写法:在遍历过程中取出字符串形式的href值,再做匹配判断
for link in soup.find_all('a', href=True): current_href = link['href'] if 'about' in current_href: print(current_href)
- 更高效率的写法:在标签查找阶段就通过自定义过滤规则完成筛选,无需遍历所有匹配a标签后再二次过滤
about_links = soup.find_all('a', href=lambda url: url and 'about' in url) for link in about_links: print(link['href'])
上述两种写法的运行结果一致,最终仅会输出目标内容:
https://www.example.com/about/2/
内容的提问来源于stack exchange,提问作者user14177720
相关产品推荐
相关产品推荐

