[英]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]
之后必須像這樣縮短字符串很麻煩。 考慮使用正則表達式一次獲得適當的格式。
問題似乎只是您擁有的尾隨空格,這解釋了錯誤ValueError: unconverted data remains:
。 它抱怨它無法轉換剩余的數據(空白)。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.