抓取新闻日期

Scraping Date of News

我正在尝试从 https://finansial.bisnis.com/read/20210506/90/1391096/laba-bank-mega-tumbuh-dua-digit-kuartal-i-2021-ini-penopangnya 进行抓取。我正在尝试抓取新闻日期,这是我的代码:

news['tanggal'] = newsScrape['date']
dates = []
for x in news['tanggal']:
    x = listToString(x)
    x = x.strip()
    x = x.replace('\r', '').replace('\n', '').replace(' \xa0|\xa0', ',').replace('|', ', ')
    dates.append(x)
dates = listToString(dates)
dates = dates[0:20]
if len(dates) == 0:
    continue
news['tanggal'] = dt.datetime.strptime(dates, '%d %B %Y, %H:%M')

但是我得到了这个错误:

ValueError: time data '06 Mei 2021, 11:32  ' does not match format '%d %B %Y, %H:%M'

我的假设是因为Mei是印尼语,同时格式需要May是英文。如何把Mei改成May?我试过 dates = dates.replace('Mei', 'May') 但它对我不起作用。当我尝试时,出现错误 ValueError: unconverted data remains: The type of dates is string。谢谢

您关于 May -> Mei 更改的假设是正确的,替换后您可能遇到问题的原因是字符串中的尾随空格,您的格式中没有考虑到这些空格。您可以使用 string.rstrip() 删除这些空格。

import datetime as dt

dates = "06 Mei 2021, 11:32  "
dates = dates.replace("Mei", "May") # The replacement will have to be handled for all months, this is only an example
dates = dates.rstrip()
date = dt.datetime.strptime(dates, "%d %B %Y, %H:%M")
print(date) # 2021-05-06 11:32:00

同时 这确实解决了这里的问题,在 dates = dates[0:20] 之后必须像这样缩短字符串很麻烦。考虑使用正则表达式立即获得适当的格式。

问题似乎只是尾随的白色 space,这解释了错误 ValueError: unconverted data remains: 。它抱怨无法转换剩余数据(whitespace)。

s = '06 Mei 2021, 11:32  '.replace('Mei', 'May').strip()
datetime.strptime(s, '%d %B %Y, %H:%M')
# Returns datetime.datetime(2021, 5, 6, 11, 32)

此外,要将所有印度尼西亚语月份转换为英语,您可以使用字典:

id_en_dict = {
    ...,
    'Mei': 'May',
    ...
}

您可以尝试以下方法

import datetime as dt
import requests
from bs4 import BeautifulSoup
import urllib.request

url="https://finansial.bisnis.com/read/20210506/90/1391096/laba-bank-mega-tumbuh-dua-digit-kuartal-i-2021-ini-penopangnya"
r = requests.get(url, verify=False)
soup = BeautifulSoup(r.content, 'html.parser')
info_soup= soup.find(class_="new-description")
x=info_soup.find('span').get_text(strip=True)
x = x.strip()
x = x.replace('\r', '').replace('\n', '').replace(' \xa0|\xa0', ',').replace('|', ', ')
x = x[0:20]
x = x.rstrip()
date= dt.datetime.strptime(x.replace('Mei', 'May'), '%d %B %Y, %H:%M')
print(date)

结果:

2021-05-06 11:45:00