首页 > 解决方案 > 如何从欧洲央行网站上抓取正确的元素

问题描述

我正在尝试从下面的网站中提取新闻声明和演讲。

我的问题与这个问题非常相似。为抓取网站找到正确的元素

from bs4 import BeautifulSoup
from selenium import webdriver

base_url = 'https://www.ecb.europa.eu'
urls = [
    f'{base_url}/press/pr/html/index.en.html',
    f'{base_url}/press/govcdec/html/index.en.html'
]
driver = webdriver.Chrome()

for url in urls:
    driver.get(url)
    soup = BeautifulSoup(driver.page_source, 'html.parser')

    for anchor in soup.select('span.doc-title > a[href]'):
        driver.get(f'{base_url}{anchor["href"]}')
        article_soup = BeautifulSoup(driver.page_source, 'html.parser')

        title = article_soup.select_one('h1.ecb-pressContentTitle').text
        date = article_soup.select_one('p.ecb-publicationDate').text
        paragraphs = article_soup.select('div.ecb-pressContent > article > p:not([class])')
        content = '\n\n'.join(p.text for p in paragraphs)

        print(f'title: {title}')
        print(f'date: {date}')
        print(f'content: {content[0:80]}...')

但是,我尝试运行它并没有得到任何输出。我在 HTML 方面的经验很少。特别是,我不明白这是循环的部分。与 CSS 相关的东西。

for anchor in soup.select('span.doc-title > a[href]'):

所以我怀疑它不再起作用了,因为最近欧洲央行网页的布局发生了变化。我猜 html 参考是变化的,但我不知道确切

非常感谢你的帮助。

标签: pythonweb-scraping

解决方案


我已经安装了 webdriver,所以这不是问题。现在我基本上刚刚删除了第二个循环并更正了元素并且它有效:)

date = article_soup.select_one('p.ecb-publicationDate').text 
title = article_soup.select_one('title').text 
subtitle = article_soup.select_one('h2.ecb-pressContentSubtitle').text
paragraphs = article_soup.select('div.section > p:not([class])')
content = '\n\n'.join(p.text for p in paragraphs)

#print(date)
#print(title)
#print(subtitle)
#print(content)

推荐阅读