-
Notifications
You must be signed in to change notification settings - Fork 2
/
date_extractor.py
273 lines (207 loc) · 8.16 KB
/
date_extractor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
"""
Python3 port of https://github.com/Webhose/article-date-extractor.
"""
import requests
import re
from dateutil.parser import parse
from bs4 import BeautifulSoup
import tldextract
import dateparser
def parseStrDate(dateString):
try:
dateTimeObj = parse(dateString)
return dateTimeObj
except:
try:
return dateparser.parse(dateString)
except:
return None
# Try to extract from the article URL - simple but might work as a fallback
def _extractFromURL(url):
#Regex by Newspaper3k - https://github.com/codelucas/newspaper/blob/master/newspaper/urls.py
m = re.search(r'([\./\-_]{0,1}(19|20)\d{2})[\./\-_]{0,1}(([0-3]{0,1}[0-9][\./\-_])|(\w{3,5}[\./\-_]))([0-3]{0,1}[0-9][\./\-]{0,1})?', url)
if m:
return parseStrDate(m.group(0))
return None
# def _extractFromLDJson(parsedHTML):
# jsonDate = None
# try:
# script = parsedHTML.find('script', type='application/ld+json')
# if script is None:
# return None
#
# data = json.loads(script.text)
#
# try:
# jsonDate = parseStrDate(data['datePublished'])
# except e:
# pass
#
# try:
# jsonDate = parseStrDate(data['dateCreated'])
# except e:
# pass
#
#
# except e:
# return None
#
#
#
# return jsonDate
def _extractFromMeta(parsedHTML):
metaDate = None
for meta in parsedHTML.findAll("meta"):
metaName = meta.get('name', '').lower()
itemProp = meta.get('itemprop', '').lower()
httpEquiv = meta.get('http-equiv', '').lower()
metaProperty = meta.get('property', '').lower()
#<meta name="pubdate" content="2015-11-26T07:11:02Z" >
if 'pubdate' == metaName:
metaDate = meta['content'].strip()
print(metaDate)
break
#<meta name='publishdate' content='201511261006'/>
if 'publishdate' == metaName:
metaDate = meta['content'].strip()
break
#<meta name="timestamp" data-type="date" content="2015-11-25 22:40:25" />
if 'timestamp' == metaName:
metaDate = meta['content'].strip()
break
#<meta name="DC.date.issued" content="2015-11-26">
if 'dc.date.issued' == metaName:
metaDate = meta['content'].strip()
break
#<meta property="article:published_time" content="2015-11-25" />
if 'article:published_time' == metaProperty:
metaDate = meta['content'].strip()
break
#<meta name="Date" content="2015-11-26" />
if 'date' == metaName:
metaDate = meta['content'].strip()
break
#<meta property="bt:pubDate" content="2015-11-26T00:10:33+00:00">
if 'bt:pubdate' == metaProperty:
metaDate = meta['content'].strip()
break
#<meta name="sailthru.date" content="2015-11-25T19:56:04+0000" />
if 'sailthru.date' == metaName:
metaDate = meta['content'].strip()
break
#<meta name="article.published" content="2015-11-26T11:53:00.000Z" />
if 'article.published' == metaName:
metaDate = meta['content'].strip()
break
#<meta name="published-date" content="2015-11-26T11:53:00.000Z" />
if 'published-date' == metaName:
metaDate = meta['content'].strip()
break
#<meta name="article.created" content="2015-11-26T11:53:00.000Z" />
if 'article.created' == metaName:
metaDate = meta['content'].strip()
break
#<meta name="article_date_original" content="Thursday, November 26, 2015, 6:42 AM" />
if 'article_date_original' == metaName:
metaDate = meta['content'].strip()
break
#<meta name="cXenseParse:recs:publishtime" content="2015-11-26T14:42Z"/>
if 'cxenseparse:recs:publishtime' == metaName:
metaDate = meta['content'].strip()
break
#<meta name="DATE_PUBLISHED" content="11/24/2015 01:05AM" />
if 'date_published' == metaName:
metaDate = meta['content'].strip()
break
#<meta itemprop="datePublished" content="2015-11-26T11:53:00.000Z" />
if 'datepublished' == itemProp:
metaDate = meta['content'].strip()
break
#<meta itemprop="datePublished" content="2015-11-26T11:53:00.000Z" />
if 'datecreated' == itemProp:
metaDate = meta['content'].strip()
break
#<meta property="og:image" content="http://www.dailytimes.com.pk/digital_images/400/2015-11-26/norway-return-number-of-asylum-seekers-to-pakistan-1448538771-7363.jpg"/>
# if 'og:image' == metaProperty or "image" == itemProp:
# url = meta['content'].strip()
# possibleDate = _extractFromURL(url)
# if possibleDate is not None:
# return possibleDate
#<meta http-equiv="data" content="10:27:15 AM Thursday, November 26, 2015">
if 'date' == httpEquiv:
metaDate = meta['content'].strip()
break
if metaDate is not None:
return parseStrDate(metaDate)
return None
def _extractFromHTMLTag(parsedHTML):
#<time>
for time in parsedHTML.findAll("time"):
datetime = time.get('datetime', '')
if len(datetime) > 0:
return parseStrDate(datetime)
datetime = time.get('class', '')
if len(datetime) > 0 and datetime[0].lower() == "timestamp":
return parseStrDate(time.string)
tag = parsedHTML.find("span", {"itemprop": "datePublished"})
if tag is not None:
dateText = tag.get("content")
if dateText is None:
dateText = tag.text
if dateText is not None:
return parseStrDate(dateText)
# class=
for tag in parsedHTML.find_all(['span', 'p','div'], class_=re.compile("pubdate|timestamp|article_date|articledate|date",re.IGNORECASE)):
dateText = tag.string
if dateText is None:
dateText = tag.text
possibleDate = parseStrDate(dateText)
if possibleDate is not None:
return possibleDate
return None
def _extractSource(parsedHTML):
source = parsedHTML.find('span', class_='field-source')
if source:
return source.text.strip()
return None
def _parseSourceFromUrl(url):
p = tldextract.extract(url)
return p.domain
def _extractCountry(parsedHTML):
countryDiv = parsedHTML.find('div', class_='primary-country')
if countryDiv:
return countryDiv.find('div', class_='country').find('a').text.strip()
return None
def extractArticlePublishedDate(articleLink, html=None):
# print("Extracting date from " + articleLink)
articleDate = None
source = None
country = None
try:
articleDate = _extractFromURL(articleLink)
if html is None:
html = requests.get(articleLink).text
# request = urllib2.Request(articleLink)
# Using a browser user agent, decreases the change of sites blocking this request - just a suggestion
# request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36')
# html = urllib2.build_opener().open(request).read()
parsedHTML = BeautifulSoup(html, "lxml")
# possibleDate = _extractFromLDJson(parsedHTML)
# if possibleDate is None:
possibleDate = _extractFromMeta(parsedHTML)
if possibleDate is None:
possibleDate = _extractFromHTMLTag(parsedHTML)
if possibleDate:
articleDate = possibleDate
source = _extractSource(parsedHTML)
country = _extractCountry(parsedHTML)
if not source:
source = _parseSourceFromUrl(articleLink)
except Exception as e:
pass
# print("Exception in extractArticlePublishedDate for " + articleLink)
# print(e.message, e.args)
return articleDate, source, country
if __name__ == '__main__':
d, s, c = extractArticlePublishedDate("http://reliefweb.int/report/bangladesh/bangladesh-rohingya-refugees-trapped-limbo")
print(d, s, c)