如何从 ECB 网站抓取正确的元素

时间:2021-03-05 12:15:35

标签: python web-scraping

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

我的问题与这个问题非常相似。 Finding the correct elements for scraping a website

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 引用发生了变化,但我不知道确切

非常感谢您的帮助。

4 个答案:

答案 0 :(得分:0)

我可以知道您确切需要什么答案吗?您可以使用 .find_all() 来查找特定标签、类或 ID 的所有元素。 标签:在字符串中输入标签的名称 类:类型 class_="TheNameOfClass" Id:输入 id="NameOFID"

希望这有帮助。如果您有任何疑问,请务必提出其他问题。

答案 1 :(得分:0)

我需要以下内容

<div class="title"> <h1>Unconventional fiscal and monetary (...) </h1>
<h2 class="ecb-pressContentSubtitle">Keynote speech by Isabel Schnabel, (...)”</h2>
<p class="ecb-publicationDate">Frankfurt am Main, 26 February 2021</p>
<p>One of the greatest conundrums (...) 

所以我的输出看起来像

title:非常规财政和货币政策(...) 副标题:伊莎贝尔·施纳贝尔的主题演讲,(...)
日期:2019年12月20日
内容:最大的难题之一(...)

答案 2 :(得分:0)

哦,好的,所以首先你会在 driver = webdriver.Chrome() 中得到一个错误。在括号内,您应该粘贴安装的 webdriver 的确切路径。如果您没有用于 chrome 的 webdriver,请按照下面给出的说明进行操作。现在,如果您在那里指定了 webdriver 路径并且不想将其泄露给其他人,那么没问题。

接下来,您可以使用 selenium 本身来抓取元素,而不是使用漂亮的汤。使用 driver.find_element_by_class_name("") 并输入您要搜索的班级名称。对于这种情况,它将是“标题”。接下来,您要获取 h1 的文本。我不完全知道如何在 selenium 中找到孩子,你可以搜索它并使用命令来获取 h1 的代码。将它存储在一个变量中,您可以像这样打印它的文本 print(h1.text)。注意:搜索如何从 selenium 获取标签的子元素,然后使用任何网站中提到的命令,然后使用 .text

说明:

  1. 检查您的 Chrome 版本
  2. 转到此网站 https://sites.google.com/a/chromium.org/chromedriver/downloads
  3. 点击与您的 Chrome 版本匹配的链接。
  4. 下载适合您电脑的版本。
  5. 解压文件并获取路径并将其粘贴到 webdriver.Chrome() 中。

仅此而已。如果我的回答没有让您满意,请务必询问,因为我不是硒专家。我也是学徒。

答案 3 :(得分:0)

我已经安装了 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)