【问题标题】:Finding the correct elements for scraping a website为抓取网站找到正确的元素
【发布时间】:2020-01-16 15:37:43
【问题描述】:

我试图只从this 主页上抓取某些文章。更具体地说,我试图仅从子页面媒体和子子页面Press releases 中抓取文章; Governing Council decisions; Press conferences; Monetary policy accounts; Speeches; Interviews,还有英文的。

我设法(基于一些教程和其他 SE:overflow 答案)整理了一个从网站上完全抓取所有内容的代码,因为我最初的想法是抓取所有内容,然后在数据框中稍后清除输出,但是网站包含的内容太多以至于它总是在一段时间后冻结。

获取子链接:

import requests
import re
from bs4 import BeautifulSoup
master_request = requests.get("https://www.ecb.europa.eu/")
base_url = "https://www.ecb.europa.eu"
master_soup = BeautifulSoup(master_request.content, 'html.parser')
master_atags = master_soup.find_all("a", href=True)
master_links = [ ] 
sub_links = {}
for master_atag in master_atags:
    master_href = master_atag.get('href')
    master_href = base_url + master_href
    print(master_href)
    master_links.append(master_href)
    sub_request = requests.get(master_href)
    sub_soup = BeautifulSoup(sub_request.content, 'html.parser')
    sub_atags = sub_soup.find_all("a", href=True)
    sub_links[master_href] = []
    for sub_atag in sub_atags:
        sub_href = sub_atag.get('href')
        sub_links[master_href].append(sub_href)
        print("\t"+sub_href)

我尝试的一些事情是将基本链接更改为子链接 - 我的想法是,也许我可以为每个子页面单独执行此操作,然后将链接放在一起,但这不起作用)。我尝试的其他方法是将第 17 行替换为以下内容;

sub_atags = sub_soup.find_all("a",{'class': ['doc-title']}, herf=True)

这似乎部分解决了我的问题,因为即使它没有只从子页面获得链接,它至少忽略了不是“doc-title”的链接,这些链接是网站上所有带有文本的链接,但它是仍然太多,一些链接没有正确检索。

我试过也试过以下:

for master_atag in master_atags:
    master_href = master_atag.get('href')
    for href in master_href:
        master_href = [base_url + master_href if str(master_href).find(".en") in master_herf
    print(master_href)

我认为因为所有带有英文文档的 href 在其中某处都有 .en,这只会给我所有链接,其中 .en 出现在 href 中的某处,但是这段代码给了我不明白的 print(master_href) 语法错误因为以前 print(master_href) 工作过。

接下来我想从子链接中提取以下信息。这部分代码在我测试单个链接时有效,但我从来没有机会在上面的代码上尝试它,因为它不会完成运行。一旦我设法获得所有链接的正确列表,这会起作用吗?

for links in sublinks:
    resp = requests.get(sublinks)
    soup = BeautifulSoup(resp.content, 'html5lib')
    article = soup.find('article')
    title = soup.find('title')
    textdate = soup.find('h2')
    paragraphs = article.find_all('p')
    matches = re.findall('(\d{2}[\/ ](\d{2}|January|Jan|February|Feb|March|Mar|April|Apr|May|May|June|Jun|July|Jul|August|Aug|September|Sep|October|Oct|November|Nov|December|Dec)[\/ ]\d{2,4})', str(textdate))
        for match in matches:
        print(match[0])
        datadate = match[0]
import pandas as pd
ecbdf = pd.DataFrame({"Article": [Article]; "Title": [title]: "Text": [paragraphs], "date": datadate})

还回到刮痧,因为第一种方法用漂亮的汤对我不起作用,我也试图以不同的方式解决这个问题。该网站有 RSS 提要,所以我想使用以下代码:

import feedparser
from pandas.io.json import json_normalize
import pandas as pd
import requests
rss_url='https://www.ecb.europa.eu/home/html/rss.en.html'
ecb_feed = feedparser.parse(rss_url) 
df_ecb_feed=json_normalize(ecb_feed.entries)
df_ecb_fead.head()

在这里我遇到了一个问题,甚至无法找到 RSS 提要 url。我尝试了以下方法:我查看了源页面并尝试搜索“RSS”并尝试了所有可以通过这种方式找到的网址,但我总是得到空的数据框。

我是网络抓取的初学者,此时我不知道如何继续或如何解决这个问题。最后,我想要完成的是从子页面中收集所有文章及其标题、日期和作者,并将它们放入一个数据框中。

【问题讨论】:

  • 我只是想了解一下,您想从链接中抓取什么?我还不清楚,例如 url 你想提取什么?
  • 你想从那个链接得到什么?
  • @αԋɱҽԃαмєяιcαη 我想把它变成数据框中的一行,列如下: pd.DataFrame({"Article": [Article]; "Title": [title]: "Text ":[段落],"日期":数据日期})。所以基本上是整篇原始文章,然后是单独的文章标题、单独的文本和单独的日期,如果有作者,那么也是这样(尽管他们中的大多数人都没有)

标签: python python-3.x web-scraping beautifulsoup


【解决方案1】:

你在抓取这个网站时遇到的最大问题可能是延迟加载:使用 JavaScript,他们从几个 html 页面加载文章并将它们合并到列表中。有关详细信息,请注意源代码中的index_include。这对于仅使用请求和 BeautifulSoup 进行抓取是有问题的,因为您的汤实例从请求内容中获得的只是没有文章列表的基本骨架。现在你有两个选择:

  1. 使用延迟加载的文章列表代替主文章列表页面(新闻稿、采访等),例如 /press/pr/date/2019/html/index_include.en.html。这可能是更简单的选择,但您必须在感兴趣的每一年都这样做。
  2. 使用像 Selenium 这样可以执行 JavaScript 的客户端来获取 HTML 而不是请求。

除此之外,我建议使用 CSS 选择器从 HTML 代码中提取信息。这样,您只需要几行文章即可。此外,如果您使用 index.en.html 页面进行抓取,我认为您不必过滤英文文章,因为它默认显示英文,并且 - 此外 - 其他语言(如果可用)。

这是我快速整理的一个示例,这当然可以优化,但它展示了如何使用 Selenium 加载页面并提取文章 URL 和文章内容:

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]}...')

我得到了新闻稿页面的以下输出:

title: ECB appoints Petra Senkovic as Director General Secretariat and Pedro Gustavo Teixeira as Director General Secretariat to the Supervisory Board                         
date: 20 December 2019                                    
content: The European Central Bank (ECB) today announced the appointments of Petra Senkov...

title: Monetary policy decisions                          
date: 12 December 2019                                    
content: At today’s meeting the Governing Council of the European Central Bank (ECB) deci...

【讨论】:

  • 在我的回答中完全忘记了一件事:既然您知道要抓取哪些页面,我还建议您遍历起始 URL 列表(在我的示例中为 urls),而不是抓取整个网站并过滤掉您不想提取的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-21
  • 2021-09-25
  • 2021-09-25
  • 2023-04-01
  • 2019-04-23
相关资源
最近更新 更多