python - 如何从欧洲央行网站上抓取正确的元素
问题描述
我正在尝试从下面的网站中提取新闻声明和演讲。
我的问题与这个问题非常相似。为抓取网站找到正确的元素
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 参考是变化的,但我不知道确切
非常感谢你的帮助。
解决方案
我已经安装了 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)
推荐阅读
- c# - Xamarin Forms:IOS adhoc 崩溃但调试有效
- c# - 在 ASP.NET 中将阿拉伯语 AM/PM 转换为英语 AM/PM
- lua - Lua - 打印函数计算的结果
- android - 使用 ContentResolver 运行 Robolectric 测试的非法连接指针
- angularjs - 通过控制器动态设置 ng-bind 值,而不是使用表达式
- jquery - jQuery动态表格点击
- javascript - React - 突出显示给定 Xpath 的危险SetHTML 内的文本
- javascript - PixiJS - 基于位置吸收光和动态音频
- emacs - Elisp 以编程方式复制到剪贴板剪贴板
- php - 使用 PHP 隐藏子行的表