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.

555 lines
25 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. # save interim results to files
  59. f = open("spiders/pages/" + key + str(i) + "entryList.html", "w+")
  60. f.write(web_content)
  61. f.close
  62. def find_config_parameter(self, list_of_fdbs):
  63. for fdb in list_of_fdbs:
  64. try:
  65. iteration_var_list = eval(self.config.get(fdb).get("entry-list").get("iteration-var-list"))
  66. except Exception as e:
  67. print(
  68. "There is a problem with the configuration variable entryList iteration var list in the config.yaml",
  69. e,
  70. )
  71. fdb_conf = self.config.get(fdb)
  72. fdb_domain = fdb_conf.get("domain")
  73. fdb_conf_entry_list = fdb_conf.get("entry-list")
  74. fdb_conf_entry_list_parent = fdb_conf_entry_list.get("parent")
  75. fdb_conf_entry_list_child_name = fdb_conf_entry_list.get("child-name")
  76. fdb_conf_entry_list_child_link = fdb_conf_entry_list.get("child-link")
  77. fdb_conf_entry_list_child_info = fdb_conf_entry_list.get("child-info")
  78. fdb_conf_entry_list_child_period = fdb_conf_entry_list.get("child-period")
  79. for i in iteration_var_list:
  80. print(i)
  81. try:
  82. # use soupparser to handle broken html
  83. tree = lxml.html.soupparser.parse(
  84. "spiders/pages/" + fdb + str(i) + "entryList.html"
  85. )
  86. except Exception as e:
  87. tree = html.parse("spiders/pages/" + fdb + str(i) + "entryList.html")
  88. print(
  89. "parsing the xml files did not work with the soupparser. Broken html will not be fixed as it could have been",
  90. e,
  91. )
  92. try:
  93. print('this is the n looped elements of the parent specified in config.yaml:')
  94. #print('entrylistparent', fdb_conf_entry_list_parent)
  95. #print(tree.xpath("//html//body//div//main//div//div[@class='row']//section[@class='l-search-result-list']"))
  96. #print(etree.tostring(tree.xpath(fdb_conf_entry_list_parent)).decode())
  97. for n in range(len(tree.xpath(fdb_conf_entry_list_parent))):
  98. print('-----------------------------------------------------------------------------------------------------------------------------------------')
  99. print(etree.tostring(tree.xpath(fdb_conf_entry_list_parent)[n]).decode())
  100. print('this is the name children:')
  101. name_element = tree.xpath(fdb_conf_entry_list_parent + fdb_conf_entry_list_child_name)
  102. print(name_element)
  103. #for name in name_element:
  104. # print(name)
  105. print(len(name_element))
  106. print('this is the link children:')
  107. link_element = tree.xpath(fdb_conf_entry_list_parent + fdb_conf_entry_list_child_link)
  108. print(link_element)
  109. #for link in link_element:
  110. # print(link)
  111. print(len(link_element))
  112. print('this is the info children:')
  113. info_element = tree.xpath(fdb_conf_entry_list_parent + fdb_conf_entry_list_child_info)
  114. print(info_element)
  115. print(len(info_element))
  116. print('this is the period children:')
  117. period_element = tree.xpath(fdb_conf_entry_list_parent + fdb_conf_entry_list_child_period)
  118. print(period_element)
  119. print(len(period_element))
  120. except Exception as e:
  121. print(
  122. "parsing the html did not work.",
  123. e,
  124. )
  125. def parse_entry_list_data2dictionary(self, list_of_fdbs):
  126. for fdb in list_of_fdbs:
  127. try:
  128. iteration_var_list = eval(self.config.get(fdb).get("entry-list").get("iteration-var-list"))
  129. except Exception as e:
  130. print(
  131. "There is a problem with the configuration variable entryList iteration var list in the config.yaml - the original error message is:",
  132. e,
  133. )
  134. for i in iteration_var_list:
  135. print(i)
  136. try:
  137. # use soupparser to handle broken html
  138. tree = lxml.html.soupparser.parse(
  139. "spiders/pages/" + fdb + str(i) + "entryList.html"
  140. )
  141. except Exception as e:
  142. tree = html.parse("spiders/pages/" + fdb + str(i) + "entryList.html")
  143. print(
  144. "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:",
  145. e,
  146. )
  147. try:
  148. #print('this is the n looped elements of the parent specified in config.yaml:')
  149. #for e in tree.iter():
  150. # print(e.tag)
  151. #
  152. #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()]"):
  153. #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']"):
  154. # print(etree.tostring(e).decode())
  155. dictionary_entry_list = {}
  156. fdb_conf = self.config.get(fdb)
  157. fdb_domain = fdb_conf.get("domain")
  158. fdb_conf_entry_list = fdb_conf.get("entry-list")
  159. fdb_conf_entry_list_parent = fdb_conf_entry_list.get("parent")
  160. fdb_conf_entry_list_child_name = fdb_conf_entry_list.get("child-name")
  161. fdb_conf_entry_list_child_link = fdb_conf_entry_list.get("child-link")
  162. fdb_conf_entry_list_child_info = fdb_conf_entry_list.get("child-info")
  163. fdb_conf_entry_list_child_period = fdb_conf_entry_list.get("child-period")
  164. #print('blabliblub')
  165. #print('len', len(tree.xpath(fdb_conf_entry_list_parent)))
  166. for n in range(len(tree.xpath(fdb_conf_entry_list_parent))):
  167. try:
  168. name = tree.xpath(
  169. fdb_conf_entry_list_parent
  170. + "["
  171. + str(n+1)
  172. + "]"
  173. + fdb_conf_entry_list_child_name
  174. )[0]
  175. except Exception as e:
  176. print("name could not be parsed", e)
  177. name = 'NONE'
  178. try:
  179. info = tree.xpath(
  180. fdb_conf_entry_list_parent
  181. + "["
  182. + str(n+1)
  183. + "]"
  184. + fdb_conf_entry_list_child_info
  185. )[0]
  186. except Exception as e:
  187. print("info could not be parsed", e, info)
  188. info = 'NONE'
  189. try:
  190. period = tree.xpath(
  191. fdb_conf_entry_list_parent
  192. + "["
  193. + str(n+1)
  194. + "]"
  195. + fdb_conf_entry_list_child_period
  196. )[0]
  197. #print('period', period)
  198. except Exception as e:
  199. print("period could not be parsed", e, period)
  200. period = 'NONE'
  201. try:
  202. link = tree.xpath(
  203. fdb_conf_entry_list_parent
  204. + "["
  205. + str(n+1)
  206. + "]"
  207. + fdb_conf_entry_list_child_link
  208. )[0]
  209. #print('link', link)
  210. except Exception as e:
  211. print("link could not be parsed", e, link)
  212. link = 'NONE'
  213. if len(name) > 0 and name != 'NONE':
  214. dictionary_entry_list[n] = {}
  215. dictionary_entry_list[n]["name"] = name
  216. dictionary_entry_list[n]["info"] = info
  217. dictionary_entry_list[n]["period"] = period
  218. if fdb_domain in link:
  219. dictionary_entry_list[n]["link"] = link
  220. if fdb_domain not in link and ('http:' in link or 'www.' in link or 'https:' in link):
  221. dictionary_entry_list[n]["link"] = link
  222. else:
  223. if link[-1] == '/':
  224. dictionary_entry_list[n]["link"] = fdb_domain + link
  225. else:
  226. dictionary_entry_list[n]["link"] = fdb_domain + '/' + link
  227. except Exception as e:
  228. print(
  229. "parsing the html did not work. Possibly you first have to run download_link_list_pages_of_funding_databases(). The original error message is:",
  230. e,
  231. )
  232. # save interim results to files
  233. f = open("spiders/output/" + fdb + str(i) + "entryList.txt", "w+")
  234. f.write(str(dictionary_entry_list))
  235. f.close
  236. def download_entry_data_htmls(self, list_of_fdbs):
  237. for fdb in list_of_fdbs:
  238. try:
  239. iteration_var_list = eval(self.config.get(fdb).get("entry-list").get("iteration-var-list"))
  240. except Exception as e:
  241. print(
  242. "There is a problem with the configuration variable entryList iteration var list in the config.yaml - the original error message is:",
  243. e,
  244. )
  245. for i in iteration_var_list:
  246. f = open("spiders/output/" + fdb + str(i) + "entryList.txt")
  247. text = f.read()
  248. dictionary_entry_list = eval(text)
  249. for entry_id in dictionary_entry_list:
  250. entry_link = dictionary_entry_list[entry_id]["link"]
  251. # download the html page of the entry
  252. try:
  253. # defining cookie to not end up in endless loop because of cookie banners pointing to redirects
  254. url = entry_link
  255. req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0', 'Cookie':'myCookie=lovely'})
  256. response = urllib.request.urlopen(req)
  257. except Exception as e:
  258. try:
  259. response = urllib.request.urlopen(entry_link.encode('ascii', errors='xmlcharrefreplace').decode('ascii'))
  260. print(
  261. "opening the link did not work, try to encode to ascii replacing xmlcharrefs now and reopen - the original error message is:",
  262. e,
  263. )
  264. except Exception as ex:
  265. print(entry_link, entry_link.encode('ascii', errors='xmlcharrefreplace').decode('ascii'), ex )
  266. try:
  267. web_content = response.read().decode("UTF-8")
  268. except Exception as e:
  269. try:
  270. web_content = response.read().decode("latin-1")
  271. print(
  272. "decoding the respone in utf8 did not work, try to decode latin1 now - the original error message is:",
  273. e,
  274. )
  275. except Exception as ex:
  276. print(ex)
  277. # save interim results to files
  278. if '.pdf' in entry_link:
  279. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  280. response = requests.get(entry_link)
  281. os.makedirs(os.path.dirname(file_name), exist_ok=True)
  282. f = open(file_name, "bw")
  283. f.write(response.content)
  284. f.close
  285. else:
  286. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  287. os.makedirs(os.path.dirname(file_name), exist_ok=True)
  288. f = open(file_name, "w+")
  289. f.write(web_content)
  290. f.close
  291. def parse_entry_data2dictionary(self, list_of_fdbs):
  292. for fdb in list_of_fdbs:
  293. try:
  294. iteration_var_list = eval(self.config.get(fdb).get("entry-list").get("iteration-var-list"))
  295. except Exception as e:
  296. print(
  297. "There is a problem with the configuration variable entryList iteration var list in the config.yaml - the original error message is:",
  298. e,
  299. )
  300. for i in iteration_var_list:
  301. print("started to parse data of entry of " + fdb + " ..")
  302. f = open("spiders/output/" + fdb + str(i) + "entryList.txt")
  303. text = f.read()
  304. dictionary_entry_list = eval(text)
  305. fdb_conf = self.config.get(fdb)
  306. fdb_domain = fdb_conf.get("domain")
  307. fdb_conf_entry = fdb_conf.get("entry")
  308. #print('balubaluba', fdb_conf_entry)
  309. fdb_conf_entry_general = fdb_conf_entry.get("general")
  310. #print(fdb_conf_entry_general)
  311. for entry_id in dictionary_entry_list:
  312. print(
  313. "started to parse data of entry with name "
  314. + dictionary_entry_list[entry_id]["name"]
  315. + " .."
  316. )
  317. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  318. try:
  319. tree = lxml.html.soupparser.parse(file_name)
  320. except Exception as e:
  321. tree = html.parse(file_name)
  322. print(
  323. "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:",
  324. e,
  325. )
  326. if fdb_conf_entry_general["uniform"] == 'TRUE':
  327. fdb_conf_entry_unitrue = fdb_conf_entry.get("unitrue")
  328. for key in fdb_conf_entry_unitrue:
  329. fdb_conf_entry_unitrue_child = fdb_conf_entry_unitrue.get(key)
  330. child = tree.xpath(
  331. fdb_conf_entry_unitrue_entry_child
  332. )
  333. #print("oi", child)
  334. if len(child) > 0:
  335. dictionary_entry_list[entry_id][key] = child[
  336. 0
  337. ]
  338. else:
  339. fdb_conf_entry_unifalse = fdb_conf_entry.get("unifalse")
  340. fdb_conf_entry_unifalse_wordlist = fdb_conf_entry_unifalse.get("wordlist")
  341. if '.pdf' in dictionary_entry_list[entry_id]["link"]:
  342. print('parsing a pdf', dictionary_entry_list[entry_id]["link"], entry_id)
  343. try:
  344. generaltext = ''
  345. for page_layout in extract_pages(file_name):
  346. for element in page_layout:
  347. if isinstance(element, LTTextContainer):
  348. generaltext += element.get_text()
  349. except Exception as e:
  350. generaltext = 'NONE'
  351. print('parsing pdf did not work, the original error is:', e )
  352. else:
  353. p_text = tree.xpath(
  354. "//p//text()"
  355. )
  356. div_text = tree.xpath(
  357. "//div//text()"
  358. )
  359. #print("oi", text)
  360. generaltext = ''
  361. for n in range(len(p_text)):
  362. if len(p_text[n]) > 0:
  363. generaltext += p_text[n] + ' '
  364. for n in range(len(div_text)):
  365. if len(div_text[n]) > 0 and div_text[n] not in p_text:
  366. generaltext += div_text[n] + ' '
  367. generaltextlist = generaltext.split(' ')
  368. if len(generaltextlist) > 5000:
  369. print('text over 1000 words for entry id', entry_id, ' number of words:', len(generaltextlist))
  370. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  371. try:
  372. with open(file_name , 'r', encoding='utf-8') as file:
  373. html_content = file.read()
  374. except Exception as e:
  375. with open(file_name , 'r', encoding='latin-1') as file:
  376. html_content = file.read()
  377. print('encoding utf8 in opening with trafilatura did not work, trying latin1, original error message is:', e)
  378. generaltext = extract(html_content)
  379. print('generaltext word count was: ', len(generaltextlist), 'but now trafilatura did the job and new wordcount is:', len(generaltext.split(' ')))
  380. if len(generaltextlist) < 2:
  381. print('no text parsed, the wc is', len(generaltextlist))
  382. print('text under 2 words for entry id', entry_id, ' number of words:', len(generaltextlist))
  383. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  384. try:
  385. with open(file_name , 'r', encoding='utf-8') as file:
  386. html_content = file.read()
  387. except Exception as e:
  388. with open(file_name , 'r', encoding='latin-1') as file:
  389. html_content = file.read()
  390. print('encoding utf8 in opening with trafilatura did not work, trying latin1, original error message is:', e)
  391. generaltext = extract(html_content)
  392. try:
  393. if len(generaltext) > 2:
  394. print('generaltext word count was: ', len(generaltextlist), 'but now trafilatura did the job and new wordcount is:', len(generaltext.split(' ')))
  395. except:
  396. print('trafilatura got this out:', generaltext , 'setting generaltext to NONE')
  397. generaltext = 'NONE'
  398. dictionary_entry_list[entry_id]["text"] = generaltext
  399. dictionary_entry_list[entry_id]["text-word-count"] = len(generaltextlist)
  400. f = open("spiders/output/" + fdb + str(i) + "entryList.txt", "w+")
  401. f.write(str(dictionary_entry_list))
  402. f.close