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.

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