当前位置: 首页 > 知识库问答 >
问题:

使用Python从多个网页中提取日期

昌山
2023-03-14

我想提取新闻文章在网站上发表的日期。对于某些网站,我有确切的html元素,其中日期/时间为(div,p,time),但在某些网站上,我没有:

以下是一些网站(德国网站)的链接:

(2020年11月3日)http://www.linden.ch/de/aktuelles/aktuellesinformationen/?action=showinfo

(2020年12月1日)http://www.reutigen.ch/de/aktuelles/aktuellesinformationen/welcome.php?action=showinfo

(10/22/2020) http://buchholterberg.ch/de/Gemeinde/Information/News/Newsmeldung?filterCategory=22

我用Python库尝试了3种不同的解决方案,例如请求htmldate日期猜测器,但我总是一无所获,或者在htmldate库的情况下,我总是得到相同的日期(2020.1.1)

from bs4 import BeautifulSoup
import requests
from htmldate import find_date
from date_guesser import guess_date, Accuracy

# Lib find_date
url = "http://www.linden.ch/de/aktuelles/aktuellesinformationen/?action=showinfo&info_id=1074226"
response = requests.get(url)
my_date = find_date(response.content, extensive_search=True)
print(my_date, '\n')


# Lib guess_date
url = "http://www.linden.ch/de/aktuelles/aktuellesinformationen/?action=showinfo&info_id=1074226"
my_date = guess_date(url=url, html=requests.get(url).text)
print(my_date.date, '\n')


# Lib Requests # I DO NOT GET last modified TAG
my_date = requests.head('http://www.linden.ch/de/aktuelles/aktuellesinformationen/?action=showinfo&info_id=1074226')
print(my_date.headers, '\n')

我做错什么了吗?

您能告诉我有没有一种方法可以从这样的网站(我没有特定的div、p和datetime元素)中提取发布日期。

重要的我想进行通用日期提取,这样我就可以将这些链接放入for循环中,并对它们运行相同的函数。

共有1个答案

东方和惬
2023-03-14

我从来没有在一些日期解析库上取得过很大的成功,所以我通常会走另一条路。我相信在你的问题中,从这些网站提取日期字符串的最佳方法是使用正则表达式。

网站:linden.ch

import requests
import re as regex
from bs4 import BeautifulSoup
from datetime import datetime

url = "http://www.linden.ch/de/aktuelles/aktuellesinformationen/?action=showinfo&info_id=1074226"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
page_body = soup.find('body')
find_date = regex.search(r'(Datum der Neuigkeit)\s(\d{1,2}\W\s\w+\W\s\d{4})', str(page_body))
reformatted_timestamp = datetime.strptime(find_date.groups()[1], '%d. %b. %Y').strftime('%d-%m-%Y')
print(reformatted_timestamp)
# print output 
03-11-2020

网站:buchholterberg。中国

import requests
import re as regex
from bs4 import BeautifulSoup
from datetime import datetime

url = "http://buchholterberg.ch/de/Gemeinde/Information/News/Newsmeldung?filterCategory=22&newsid=905"
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
page_body = soup.find('body')
find_date = regex.search(r'(Veröffentlicht)\s\w+:\s(\d{1,2}:\d{1,2}:\d{1,2})\s(\d{1,2}.\d{1,2}.\d{4})', str(page_body))
reformatted_timestamp = datetime.strptime(find_date.groups()[2], '%d.%m.%Y').strftime('%d-%m-%Y')
print(reformatted_timestamp)
# print output
22-10-2020

我看了两个Python库的源代码:你提到的htmldate和date_guesser。这两个库目前都无法从您在问题中列出的3个源中提取日期。缺乏提取的主要原因与这些目标网站的日期格式和语言(德语)有关。

我有一些空闲时间,所以我为你准备了这个。下面的答案可以很容易地修改以从任何网站中提取,并且可以根据您的目标源的格式根据需要进行细化。它当前从URL中包含的所有链接中提取。

所有URL

import requests
import re as regex
from bs4 import BeautifulSoup

def extract_date(can_of_soup):
   page_body = can_of_soup.find('body')
   clean_body = ''.join(str(page_body).replace('\n', ''))
   if 'Datum der Neuigkeit' in clean_body or 'Veröffentlicht' in clean_body:
     date_formats = '(Datum der Neuigkeit)\s(\d{1,2}\W\s\w+\W\s\d{4})|(Veröffentlicht am: \d{2}:\d{2}:\d{2} )(\d{1,2}.\d{1,2}.\d{4})'
     find_date = regex.search(date_formats, clean_body, regex.IGNORECASE)
     if find_date:
        clean_tuples = [i for i in list(find_date.groups()) if i]
        return ''.join(clean_tuples[1])
   else:
       tags = ['extra', 'elementStandard elementText', 'icms-block icms-information-date icms-text-gemeinde-color']
       for tag in tags:
          date_tag = page_body.find('div', {'class': f'{tag}'})
          if date_tag is not None:
            children = date_tag.findChildren()
            if children:
                find_date = regex.search(r'(\d{1,2}.\d{1,2}.\d{4})', str(children))
                return ''.join(find_date.groups())
            else:
                return ''.join(date_tag.contents)


def get_soup(target_url):
   response = requests.get(target_url)
   soup = BeautifulSoup(response.content, 'html.parser')
   return soup


urls = {'http://www.linden.ch/de/aktuelles/aktuellesinformationen/?action=showinfo&info_id=1074226',
    'http://www.reutigen.ch/de/aktuelles/aktuellesinformationen/welcome.php?action=showinfo&info_id=1066837&ls=0'
    '&sq=&kategorie_id=&date_from=&date_to=',
    'http://buchholterberg.ch/de/Gemeinde/Information/News/Newsmeldung?filterCategory=22&newsid=905',
    'https://www.steffisburg.ch/de/aktuelles/meldungen/Hochwasserschutz-und-Laengsvernetzung-Zulg.php',
    'https://www.wallisellen.ch/aktuellesinformationen/924227',
    'http://www.winkel.ch/de/aktuellesre/aktuelles/aktuellesinformationen/welcome.php?action=showinfo&info_id'
    '=1093910&ls=0&sq=&kategorie_id=&date_from=&date_to=',
    'https://www.aeschi.ch/de/aktuelles/mitteilungen/artikel/?tx_news_pi1%5Bnews%5D=87&tx_news_pi1%5Bcontroller%5D=News&tx_news_pi1%5Baction%5D=detail&cHash=ab4d329e2f1529d6e3343094b416baed'}


for url in urls:
   html = get_soup(url)
   article_date = extract_date(html)
   print(article_date)
 类似资料:
  • 我想刮从多个网站与类似的网址的,如https://woollahra.ljhooker.com.au/our-team, https://chinatown.ljhooker.com.au/our-team和https://bondibeach.ljhooker.com.au/our-team. 我已经写了一个脚本,第一个网站的工作,但我不知道如何告诉它从其他两个网站刮。 我的代码: 有没有一种方

  • 我正在尝试制作一个python脚本,用我所拥有的有限知识从一个网页中刮取特定的信息。但我想我有限的知识是不够的。我需要提取7-8条信息。标签如下- 1 我已使用此代码开始

  • 最近,我一直试图从一个网站上获取大量的定价,从一个页面开始,每个项目的页面都链接到起始页面。我希望运行一个脚本,允许我单击某个项目的框,删除该项目的定价和描述,然后返回起始页并继续该循环。然而,有一个明显的问题,我在刮掉第一件物品后遇到了。返回起始页后,容器没有定义,因此出现了一个陈旧的元素错误,该错误会中断循环并阻止我获取其余的项。这是我使用的示例代码,希望能够一个接一个地刮去所有项目。 然而,

  • 为了我的设备,我想从戴尔网站上提取一些日期。我试图使用下载网页,但它受验证码保护,目前我无法绕过它。现在我使用Selenium打开浏览器,手动解决capthca问题,然后自动打开页面并提取日期。问题是css选择器返回的是一些奇怪的元素,而不是所需的输出 我的代码: 预期产出: 给定输出:

  • 问题内容: 使用Java,如何从给定的网页中提取所有链接? 问题答案: 将Java文件下载为纯文本/ html格式,并通过Jsoup或 html clean传递,两者相似,甚至可以用于解析格式错误的html 4.0语法,然后可以使用流行的HTML DOM解析方法,例如getElementsByName(“ a”)或在jsoup中它甚至很酷,您只需使用 并找到所有链接,然后使用 取自http://j

  • 打印出以下内容 我如何只提取第6行,即并将其放入一个数组中,其中每个元素都是逗号前的单词(例如:[0]=Alex,[1]=Cook等)