You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

607 lines
28 KiB

  1. import os
  2. import yaml
  3. import json
  4. import urllib.request, urllib.error, urllib.parse
  5. from lxml import etree
  6. import lxml.html
  7. import lxml.html.soupparser
  8. from lxml import html
  9. import requests
  10. from trafilatura import extract
  11. from pdfminer.high_level import extract_pages
  12. from pdfminer.layout import LTTextContainer
  13. class fdb_spider(object):
  14. def __init__(self, config_file):
  15. with open(config_file, "r") as stream:
  16. try:
  17. self.config = yaml.safe_load(stream)
  18. except yaml.YAMLError as exc:
  19. print(exc)
  20. # input list of funding databases in form of yaml file ['foerderinfo.bund.de', 'ausschreibungen.giz.de', .. , 'usw']
  21. def download_entry_list_pages_of_funding_databases(self, list_of_fdbs):
  22. # download only html pages of the funding databases specified in input
  23. for fdb in list_of_fdbs:
  24. for key in self.config:
  25. if key in list_of_fdbs:
  26. try:
  27. entry_list = self.config.get(key).get("entry-list")
  28. except Exception as e:
  29. print(
  30. "There is a problem with the configuration variable entryList in the config.yaml - the original error message is:",
  31. e,
  32. )
  33. try:
  34. entry_list_link1 = entry_list.get("link1")
  35. except Exception as e:
  36. print(
  37. "No link1 defined in config.yaml - the original error message is:",
  38. e,
  39. )
  40. try:
  41. entry_list_link2 = entry_list.get("link2")
  42. except Exception as e:
  43. print(
  44. "No link2 defined in config.yaml - the original error message is:",
  45. e,
  46. )
  47. try:
  48. entry_iteration_var_list = eval(entry_list.get("iteration-var-list"))
  49. except Exception as e:
  50. print(
  51. "No iteration-var-list defined in config.yaml - the original error message is:",
  52. e,
  53. )
  54. for i in entry_iteration_var_list:
  55. # download the html page of the List of entrys
  56. response = urllib.request.urlopen(entry_list_link1 + str(i) + entry_list_link2)
  57. # web_content = response.read().decode("UTF-8")
  58. try:
  59. web_content = response.read().decode("UTF-8")
  60. except Exception as e:
  61. try:
  62. web_content = response.read().decode("latin-1")
  63. print(
  64. "decoding the respone in utf8 did not work, try to decode latin1 now - the original error message is:",
  65. e,
  66. )
  67. except Exception as ex:
  68. print(ex)
  69. # save interim results to files
  70. if (len(web_content)) < 10:
  71. print('getting the html page through urllib did not work, trying with requests librarys function get')
  72. try:
  73. res = requests.get(entry_list_link1 + str(i) + entry_list_link2)
  74. web_content = res.text
  75. except Exception as e:
  76. print('also requests library did not work, original error is:', e)
  77. print(web_content)
  78. f = open("spiders/pages/" + key + str(i) + "entryList.html", "w+")
  79. f.write(web_content)
  80. f.close
  81. def find_config_parameter(self, list_of_fdbs):
  82. for fdb in list_of_fdbs:
  83. try:
  84. iteration_var_list = eval(self.config.get(fdb).get("entry-list").get("iteration-var-list"))
  85. except Exception as e:
  86. print(
  87. "There is a problem with the configuration variable entryList iteration var list in the config.yaml",
  88. e,
  89. )
  90. fdb_conf = self.config.get(fdb)
  91. fdb_domain = fdb_conf.get("domain")
  92. fdb_conf_entry_list = fdb_conf.get("entry-list")
  93. fdb_conf_entry_list_parent = fdb_conf_entry_list.get("parent")
  94. fdb_conf_entry_list_child_name = fdb_conf_entry_list.get("child-name")
  95. fdb_conf_entry_list_child_link = fdb_conf_entry_list.get("child-link")
  96. fdb_conf_entry_list_child_info = fdb_conf_entry_list.get("child-info")
  97. fdb_conf_entry_list_child_period = fdb_conf_entry_list.get("child-period")
  98. for i in iteration_var_list:
  99. print(i)
  100. try:
  101. # use soupparser to handle broken html
  102. tree = lxml.html.soupparser.parse(
  103. "spiders/pages/" + fdb + str(i) + "entryList.html"
  104. )
  105. except Exception as e:
  106. tree = html.parse("spiders/pages/" + fdb + str(i) + "entryList.html")
  107. print(
  108. "parsing the xml files did not work with the soupparser. Broken html will not be fixed as it could have been",
  109. e,
  110. )
  111. try:
  112. print('this is the n looped elements of the parent specified in config.yaml:')
  113. #print('entrylistparent', fdb_conf_entry_list_parent)
  114. #print(tree.xpath("//html//body//div//main//div//div[@class='row']//section[@class='l-search-result-list']"))
  115. #print(etree.tostring(tree.xpath(fdb_conf_entry_list_parent)).decode())
  116. for n in range(len(tree.xpath(fdb_conf_entry_list_parent))):
  117. print('-----------------------------------------------------------------------------------------------------------------------------------------')
  118. print(etree.tostring(tree.xpath(fdb_conf_entry_list_parent)[n]).decode())
  119. print('this is the name children:')
  120. name_element = tree.xpath(fdb_conf_entry_list_parent + fdb_conf_entry_list_child_name)
  121. print(name_element)
  122. #for name in name_element:
  123. # print(name)
  124. print(len(name_element))
  125. print('this is the link children:')
  126. link_element = tree.xpath(fdb_conf_entry_list_parent + fdb_conf_entry_list_child_link)
  127. print(link_element)
  128. #for link in link_element:
  129. # print(link)
  130. print(len(link_element))
  131. print('this is the info children:')
  132. info_element = tree.xpath(fdb_conf_entry_list_parent + fdb_conf_entry_list_child_info)
  133. print(info_element)
  134. print(len(info_element))
  135. print('this is the period children:')
  136. period_element = tree.xpath(fdb_conf_entry_list_parent + fdb_conf_entry_list_child_period)
  137. print(period_element)
  138. print(len(period_element))
  139. except Exception as e:
  140. print(
  141. "parsing the html did not work.",
  142. e,
  143. )
  144. def parse_entry_list_data2dictionary(self, list_of_fdbs):
  145. for fdb in list_of_fdbs:
  146. try:
  147. iteration_var_list = eval(self.config.get(fdb).get("entry-list").get("iteration-var-list"))
  148. except Exception as e:
  149. print(
  150. "There is a problem with the configuration variable entryList iteration var list in the config.yaml - the original error message is:",
  151. e,
  152. )
  153. for i in iteration_var_list:
  154. print(i)
  155. try:
  156. # use soupparser to handle broken html
  157. tree = lxml.html.soupparser.parse(
  158. "spiders/pages/" + fdb + str(i) + "entryList.html"
  159. )
  160. except Exception as e:
  161. tree = html.parse("spiders/pages/" + fdb + str(i) + "entryList.html")
  162. print(
  163. "parsing the xml files did not work with the soupparser. Broken html will not be fixed as it could have been, thanks to efficient particular html languages. The original error message is:",
  164. e,
  165. )
  166. try:
  167. #print('this is the n looped elements of the parent specified in config.yaml:')
  168. #for e in tree.iter():
  169. # print(e.tag)
  170. #
  171. #for e in tree.xpath("//html//body//div//main//div//div[@class='row']//section[@class='l-search-result-list']//div//div[@class='c-search-result__text-wrapper']//span[@class='c-search-result__title'][text()]"):
  172. #for e in tree.xpath("//html//body//div//main//div//div[@class='row']//section[@class='l-search-result-list']//div//div[@class='c-search-result__text-wrapper']//span[@class='c-search-result__title']"):
  173. # print(etree.tostring(e).decode())
  174. dictionary_entry_list = {}
  175. fdb_conf = self.config.get(fdb)
  176. fdb_domain = fdb_conf.get("domain")
  177. fdb_conf_entry_list = fdb_conf.get("entry-list")
  178. fdb_conf_entry_list_parent = fdb_conf_entry_list.get("parent")
  179. fdb_conf_entry_list_child_name = fdb_conf_entry_list.get("child-name")
  180. fdb_conf_entry_list_child_link = fdb_conf_entry_list.get("child-link")
  181. fdb_conf_entry_list_child_info = fdb_conf_entry_list.get("child-info")
  182. fdb_conf_entry_list_child_period = fdb_conf_entry_list.get("child-period")
  183. #print('blabliblub')
  184. #print('len', len(tree.xpath(fdb_conf_entry_list_parent)))
  185. for n in range(len(tree.xpath(fdb_conf_entry_list_parent))):
  186. try:
  187. name = tree.xpath(
  188. fdb_conf_entry_list_parent
  189. + "["
  190. + str(n+1)
  191. + "]"
  192. + fdb_conf_entry_list_child_name
  193. )[0]
  194. except Exception as e:
  195. print("name could not be parsed", e)
  196. name = 'NONE'
  197. try:
  198. info = tree.xpath(
  199. fdb_conf_entry_list_parent
  200. + "["
  201. + str(n+1)
  202. + "]"
  203. + fdb_conf_entry_list_child_info
  204. )[0]
  205. except Exception as e:
  206. print("info could not be parsed", e, info)
  207. info = 'NONE'
  208. try:
  209. period = tree.xpath(
  210. fdb_conf_entry_list_parent
  211. + "["
  212. + str(n+1)
  213. + "]"
  214. + fdb_conf_entry_list_child_period
  215. )[0]
  216. #print('period', period)
  217. except Exception as e:
  218. print("period could not be parsed", e, period)
  219. period = 'NONE'
  220. try:
  221. link = tree.xpath(
  222. fdb_conf_entry_list_parent
  223. + "["
  224. + str(n+1)
  225. + "]"
  226. + fdb_conf_entry_list_child_link
  227. )[0]
  228. if 'javascript:' in link:
  229. #from selenium import webdriver
  230. print('link is javascript element, not url to parse')
  231. #url = 'https://example.com'
  232. #driver = webdriver.Chrome()
  233. #driver.get(url)
  234. #links = [link.get_attribute('href') for link in driver.find_elements_by_tag_name('a')]
  235. #print('link', link)
  236. except Exception as e:
  237. print("link could not be parsed", e, link)
  238. link = 'NONE'
  239. if len(name) > 0 and name != 'NONE':
  240. dictionary_entry_list[n] = {}
  241. dictionary_entry_list[n]["name"] = name
  242. dictionary_entry_list[n]["info"] = info
  243. dictionary_entry_list[n]["period"] = period
  244. if fdb_domain in link:
  245. dictionary_entry_list[n]["link"] = link
  246. if fdb_domain not in link and ('http:' in link or 'www.' in link or 'https:' in link):
  247. dictionary_entry_list[n]["link"] = link
  248. if 'javascript:' in link:
  249. dictionary_entry_list[n]["link"] = link
  250. else:
  251. if link[-1] == '/':
  252. dictionary_entry_list[n]["link"] = fdb_domain + link
  253. else:
  254. dictionary_entry_list[n]["link"] = fdb_domain + '/' + link
  255. except Exception as e:
  256. print(
  257. "parsing the html did not work. Possibly you first have to run download_link_list_pages_of_funding_databases(). The original error message is:",
  258. e,
  259. )
  260. # save interim results to files
  261. f = open("spiders/output/" + fdb + str(i) + "entryList.txt", "w+")
  262. f.write(str(dictionary_entry_list))
  263. f.close
  264. def download_entry_data_htmls(self, list_of_fdbs):
  265. for fdb in list_of_fdbs:
  266. try:
  267. iteration_var_list = eval(self.config.get(fdb).get("entry-list").get("iteration-var-list"))
  268. except Exception as e:
  269. print(
  270. "There is a problem with the configuration variable entryList iteration var list in the config.yaml - the original error message is:",
  271. e,
  272. )
  273. for i in iteration_var_list:
  274. f = open("spiders/output/" + fdb + str(i) + "entryList.txt")
  275. text = f.read()
  276. dictionary_entry_list = eval(text)
  277. for entry_id in dictionary_entry_list:
  278. entry_link = dictionary_entry_list[entry_id]["link"]
  279. # download the html page of the entry
  280. try:
  281. # defining cookie to not end up in endless loop because of cookie banners pointing to redirects
  282. url = entry_link
  283. req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0', 'Cookie':'myCookie=lovely'})
  284. response = urllib.request.urlopen(req)
  285. except Exception as e:
  286. try:
  287. response = urllib.request.urlopen(entry_link.encode('ascii', errors='xmlcharrefreplace').decode('ascii'))
  288. print(
  289. "opening the link did not work, try to encode to ascii replacing xmlcharrefs now and reopen - the original error message is:",
  290. e,
  291. )
  292. except Exception as ex:
  293. print(entry_link, entry_link.encode('ascii', errors='xmlcharrefreplace').decode('ascii'), ex )
  294. try:
  295. web_content = response.read().decode("UTF-8")
  296. except Exception as e:
  297. try:
  298. web_content = response.read().decode("latin-1")
  299. print(
  300. "decoding the respone in utf8 did not work, try to decode latin1 now - the original error message is:",
  301. e,
  302. )
  303. except Exception as ex:
  304. print(ex)
  305. # save interim results to files
  306. if '.pdf' in entry_link:
  307. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  308. response = requests.get(entry_link)
  309. os.makedirs(os.path.dirname(file_name), exist_ok=True)
  310. f = open(file_name, "bw")
  311. f.write(response.content)
  312. f.close
  313. else:
  314. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  315. if not web_content:
  316. print('other downloading approaches did not work, trying requests')
  317. try:
  318. from requests_html import HTMLSession
  319. session = HTMLSession()
  320. r = session.get(entry_link)
  321. r.html.render()
  322. web_content = r.text
  323. except Exception as e:
  324. print('requests_html HTMLSession did not work')
  325. os.makedirs(os.path.dirname(file_name), exist_ok=True)
  326. f = open(file_name, "w+")
  327. f.write(web_content)
  328. f.close
  329. def parse_entry_data2dictionary(self, list_of_fdbs):
  330. for fdb in list_of_fdbs:
  331. try:
  332. iteration_var_list = eval(self.config.get(fdb).get("entry-list").get("iteration-var-list"))
  333. except Exception as e:
  334. print(
  335. "There is a problem with the configuration variable entryList iteration var list in the config.yaml - the original error message is:",
  336. e,
  337. )
  338. for i in iteration_var_list:
  339. print("started to parse data of entry of " + fdb + " ..")
  340. f = open("spiders/output/" + fdb + str(i) + "entryList.txt")
  341. text = f.read()
  342. dictionary_entry_list = eval(text)
  343. fdb_conf = self.config.get(fdb)
  344. fdb_domain = fdb_conf.get("domain")
  345. fdb_conf_entry = fdb_conf.get("entry")
  346. #print('balubaluba', fdb_conf_entry)
  347. fdb_conf_entry_general = fdb_conf_entry.get("general")
  348. #print(fdb_conf_entry_general)
  349. for entry_id in dictionary_entry_list:
  350. print(
  351. "started to parse data of entry with name "
  352. + dictionary_entry_list[entry_id]["name"]
  353. + " .."
  354. )
  355. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  356. try:
  357. tree = lxml.html.soupparser.parse(file_name)
  358. except Exception as e:
  359. tree = html.parse(file_name)
  360. print(
  361. "parsing the xml files did not work with the soupparser. Broken html will not be fixed as it could have been, thanks to efficient particular html languages. The original error message is:",
  362. e,
  363. )
  364. if fdb_conf_entry_general["uniform"] == 'TRUE':
  365. fdb_conf_entry_unitrue = fdb_conf_entry.get("unitrue")
  366. for key in fdb_conf_entry_unitrue:
  367. fdb_conf_entry_unitrue_child = fdb_conf_entry_unitrue.get(key)
  368. child = tree.xpath(
  369. fdb_conf_entry_unitrue_entry_child
  370. )
  371. #print("oi", child)
  372. if len(child) > 0:
  373. dictionary_entry_list[entry_id][key] = child[
  374. 0
  375. ]
  376. else:
  377. fdb_conf_entry_unifalse = fdb_conf_entry.get("unifalse")
  378. fdb_conf_entry_unifalse_wordlist = fdb_conf_entry_unifalse.get("wordlist")
  379. if '.pdf' in dictionary_entry_list[entry_id]["link"]:
  380. print('parsing a pdf', dictionary_entry_list[entry_id]["link"], entry_id)
  381. try:
  382. generaltext = ''
  383. for page_layout in extract_pages(file_name):
  384. for element in page_layout:
  385. if isinstance(element, LTTextContainer):
  386. generaltext += element.get_text()
  387. except Exception as e:
  388. generaltext = 'NONE'
  389. print('parsing pdf did not work, the original error is:', e )
  390. else:
  391. p_text = tree.xpath(
  392. "//p//text()"
  393. )
  394. div_text = tree.xpath(
  395. "//div//text()"
  396. )
  397. #print("oi", text)
  398. generaltext = ''
  399. for n in range(len(p_text)):
  400. if len(p_text[n]) > 0:
  401. generaltext += p_text[n] + ' '
  402. for n in range(len(div_text)):
  403. if len(div_text[n]) > 0 and div_text[n] not in p_text:
  404. generaltext += div_text[n] + ' '
  405. generaltextlist = generaltext.split(' ')
  406. if len(generaltextlist) > 5000:
  407. print('text over 1000 words for entry id', entry_id, ' number of words:', len(generaltextlist))
  408. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  409. try:
  410. with open(file_name , 'r', encoding='utf-8') as file:
  411. html_content = file.read()
  412. except Exception as e:
  413. with open(file_name , 'r', encoding='latin-1') as file:
  414. html_content = file.read()
  415. print('encoding utf8 in opening with trafilatura did not work, trying latin1, original error message is:', e)
  416. generaltext = extract(html_content)
  417. print('generaltext word count was: ', len(generaltextlist), 'but now trafilatura did the job and new wordcount is:', len(generaltext.split(' ')))
  418. if len(generaltextlist) < 2:
  419. print('no text parsed, the wc is', len(generaltextlist))
  420. print('text under 2 words for entry id', entry_id, ' number of words:', len(generaltextlist))
  421. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  422. try:
  423. with open(file_name , 'r', encoding='utf-8') as file:
  424. html_content = file.read()
  425. except Exception as e:
  426. with open(file_name , 'r', encoding='latin-1') as file:
  427. html_content = file.read()
  428. print('encoding utf8 in opening with trafilatura did not work, trying latin1, original error message is:', e)
  429. generaltext = extract(html_content)
  430. try:
  431. if len(generaltext) > 2:
  432. print('generaltext word count was: ', len(generaltextlist), 'but now trafilatura did the job and new wordcount is:', len(generaltext.split(' ')))
  433. except:
  434. print('trafilatura got this out:', generaltext , 'setting generaltext to NONE')
  435. generaltext = 'NONE'
  436. dictionary_entry_list[entry_id]["text"] = generaltext
  437. dictionary_entry_list[entry_id]["text-word-count"] = len(generaltextlist)
  438. f = open("spiders/output/" + fdb + str(i) + "entryList.txt", "w+")
  439. f.write(str(dictionary_entry_list))
  440. f.close