首页 > 解决方案 > 如何从网站获取某些链接,但不是全部?

问题描述

这是我到目前为止所拥有的:

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 主页上出现的文章的链接?

标签: pythonbeautifulsouppython-requests

解决方案


您可以使用列表理解对其进行过滤:

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)

推荐阅读