python - 如何从网站获取某些链接,但不是全部?
问题描述
这是我到目前为止所拥有的:
import requests
from bs4 import BeautifulSoup
def linkScraper():
html = requests.get("https://www.bbc.com/").text
soup = BeautifulSoup(html, 'html.parser')
for link in soup.find_all('a'):
print(link.get('href'))
但这会打印网站上的每个链接。我如何配置它以向我提供 BBC 主页上出现的文章的链接?
解决方案
您可以使用列表理解对其进行过滤:
import requests
from bs4 import BeautifulSoup
def linkScraper():
html = requests.get("https://www.bbc.com/").text
soup = BeautifulSoup(html, 'html.parser')
links = [link['href'] for link in soup.find_all('a') if link['href'].startswith('https://www.bbc.com/')]
for i in links:
print(i)
推荐阅读
- linux - 如何在 sed 中使用“Unix 内置命令”
- java - FooProvider/FooManager 和 Foo 对象的 Java 创建设计模式
- javascript - 如何让 discord.js 机器人仅在用户响应后回复一系列 DM 消息?
- node.js - Visual Studio 代码调试器不适用于我的 Nodejs 应用程序
- delphi - Delphi中的划分混乱
- elasticsearch - 是否可以在运行时更改 ElasticSearch 设置?
- angular - 将 Spring Boot - Angular 2 应用程序升级到 Angular 8 给出空白屏幕
- javascript - iOS Safari:使用深度链接,安装应用程序时如何防止打开应用程序商店?
- python - 提高代码性能并摆脱循环
- c# - 数据不会在所有绑定上更新