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.

660 lines
30 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. from selenium import webdriver
  266. options = webdriver.ChromeOptions()
  267. options.add_argument('headless')
  268. driver = webdriver.Chrome(options=options)
  269. for fdb in list_of_fdbs:
  270. try:
  271. iteration_var_list = eval(self.config.get(fdb).get("entry-list").get("iteration-var-list"))
  272. except Exception as e:
  273. print(
  274. "There is a problem with the configuration variable entryList iteration var list in the config.yaml - the original error message is:",
  275. e,
  276. )
  277. for i in iteration_var_list:
  278. f = open("spiders/output/" + fdb + str(i) + "entryList.txt")
  279. text = f.read()
  280. dictionary_entry_list = eval(text)
  281. fdb_conf = self.config.get(fdb)
  282. fdb_domain = fdb_conf.get("domain")
  283. fdb_conf_entry_list = fdb_conf.get("entry-list")
  284. fdb_conf_entry_list_parent = fdb_conf_entry_list.get("parent")
  285. fdb_conf_entry_list_child_name = fdb_conf_entry_list.get("child-name")
  286. try:
  287. fdb_conf_entry_list_javascript_link = fdb_conf_entry_list.get("javascript-link")
  288. except Exception as e:
  289. print('the javascript link in the config is missing, original error message is:', e)
  290. fdb_conf_entry_list_link1 = fdb_conf_entry_list.get("link1")
  291. fdb_conf_entry_list_link2 = fdb_conf_entry_list.get("link2")
  292. driver.get(fdb_conf_entry_list_link1 + str(i) + fdb_conf_entry_list_link2)
  293. for entry_id in dictionary_entry_list:
  294. entry_link = dictionary_entry_list[entry_id]["link"]
  295. web_content = 'NONE'
  296. # download the html page of the entry
  297. if 'javascript' in entry_link:
  298. element = driver.find_element(
  299. "xpath",
  300. fdb_conf_entry_list_parent
  301. + "["
  302. + str(entry_id+1)
  303. + "]"
  304. + fdb_conf_entry_list_javascript_link
  305. )
  306. element.click()
  307. window_after = driver.window_handles[1]
  308. driver.switch_to.window(window_after)
  309. element = driver.find_element("xpath", "//html")
  310. web_content = element.text
  311. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  312. os.makedirs(os.path.dirname(file_name), exist_ok=True)
  313. f = open(file_name, "w+")
  314. f.write(web_content)
  315. f.close
  316. window_before = driver.window_handles[0]
  317. driver.switch_to.window(window_before)
  318. if ('http' or 'www') in entry_link and ('javascript' or 'js' or '.pdf') not in enry_link:
  319. try:
  320. # defining cookie to not end up in endless loop because of cookie banners pointing to redirects
  321. url = entry_link
  322. req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0', 'Cookie':'myCookie=lovely'})
  323. response = urllib.request.urlopen(req)
  324. except Exception as e:
  325. try:
  326. response = urllib.request.urlopen(entry_link.encode('ascii', errors='xmlcharrefreplace').decode('ascii'))
  327. print(
  328. "opening the link did not work, try to encode to ascii replacing xmlcharrefs now and reopen - the original error message is:",
  329. e,
  330. )
  331. except Exception as ex:
  332. print(entry_link, entry_link.encode('ascii', errors='xmlcharrefreplace').decode('ascii'), ex )
  333. try:
  334. web_content = response.read().decode("UTF-8")
  335. except Exception as e:
  336. try:
  337. web_content = response.read().decode("latin-1")
  338. print(
  339. "decoding the respone in utf8 did not work, try to decode latin1 now - the original error message is:",
  340. e,
  341. )
  342. except Exception as ex:
  343. print(ex)
  344. # save interim results to files
  345. if '.pdf' in entry_link:
  346. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  347. response = requests.get(entry_link)
  348. os.makedirs(os.path.dirname(file_name), exist_ok=True)
  349. f = open(file_name, "bw")
  350. f.write(response.content)
  351. f.close
  352. else:
  353. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  354. if web_content == 'NONE':
  355. print('other downloading approaches did not work, trying requests')
  356. try:
  357. from requests_html import HTMLSession
  358. session = HTMLSession()
  359. r = session.get(entry_link)
  360. r.html.render()
  361. web_content = r.text
  362. except Exception as e:
  363. print('requests_html HTMLSession did not work')
  364. os.makedirs(os.path.dirname(file_name), exist_ok=True)
  365. f = open(file_name, "w+")
  366. f.write(web_content)
  367. f.close
  368. def parse_entry_data2dictionary(self, list_of_fdbs):
  369. for fdb in list_of_fdbs:
  370. try:
  371. fdb_config = self.config.get(fdb)
  372. print('oi oi',fdb_config)
  373. fdb_config_entrylist = fdb_config.get("entry-list")
  374. iteration_var_list = eval(fdb_config_entrylist.get("iteration-var-list"))
  375. except Exception as e:
  376. print(
  377. "There is a problem with the configuration variable entryList iteration var list in the config.yaml - the original error message is:",
  378. e,
  379. )
  380. for i in iteration_var_list:
  381. print("started to parse data of entry of " + fdb + " ..")
  382. f = open("spiders/output/" + fdb + str(i) + "entryList.txt")
  383. text = f.read()
  384. dictionary_entry_list = eval(text)
  385. fdb_conf = self.config.get(fdb)
  386. fdb_domain = fdb_conf.get("domain")
  387. fdb_conf_entry = fdb_conf.get("entry")
  388. #print('balubaluba', fdb_conf_entry)
  389. fdb_conf_entry_general = fdb_conf_entry.get("general")
  390. #print(fdb_conf_entry_general)
  391. for entry_id in dictionary_entry_list:
  392. print(
  393. "started to parse data of entry with name "
  394. + dictionary_entry_list[entry_id]["name"]
  395. + " .."
  396. )
  397. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  398. try:
  399. tree = lxml.html.soupparser.parse(file_name)
  400. except Exception as e:
  401. tree = html.parse(file_name)
  402. print(
  403. "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:",
  404. e,
  405. )
  406. if fdb_conf_entry_general["uniform"] == 'TRUE':
  407. fdb_conf_entry_unitrue = fdb_conf_entry.get("unitrue")
  408. for key in fdb_conf_entry_unitrue:
  409. fdb_conf_entry_unitrue_child = fdb_conf_entry_unitrue.get(key)
  410. child = tree.xpath(
  411. fdb_conf_entry_unitrue_entry_child
  412. )
  413. #print("oi", child)
  414. if len(child) > 0:
  415. dictionary_entry_list[entry_id][key] = child[
  416. 0
  417. ]
  418. else:
  419. fdb_conf_entry_unifalse = fdb_conf_entry.get("unifalse")
  420. fdb_conf_entry_unifalse_wordlist = fdb_conf_entry_unifalse.get("wordlist")
  421. if '.pdf' in dictionary_entry_list[entry_id]["link"]:
  422. print('parsing a pdf', dictionary_entry_list[entry_id]["link"], entry_id)
  423. try:
  424. generaltext = ''
  425. for page_layout in extract_pages(file_name):
  426. for element in page_layout:
  427. if isinstance(element, LTTextContainer):
  428. generaltext += element.get_text()
  429. except Exception as e:
  430. generaltext = 'NONE'
  431. print('parsing pdf did not work, the original error is:', e )
  432. else:
  433. p_text = tree.xpath(
  434. "//p//text()"
  435. )
  436. div_text = tree.xpath(
  437. "//div//text()"
  438. )
  439. #print("oi", text)
  440. generaltext = ''
  441. for n in range(len(p_text)):
  442. if len(p_text[n]) > 0:
  443. generaltext += p_text[n] + ' '
  444. for n in range(len(div_text)):
  445. if len(div_text[n]) > 0 and div_text[n] not in p_text:
  446. generaltext += div_text[n] + ' '
  447. generaltextlist = generaltext.split(' ')
  448. if len(generaltextlist) > 5000:
  449. print('text over 1000 words for entry id', entry_id, ' number of words:', len(generaltextlist))
  450. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  451. try:
  452. with open(file_name , 'r', encoding='utf-8') as file:
  453. html_content = file.read()
  454. except Exception as e:
  455. with open(file_name , 'r', encoding='latin-1') as file:
  456. html_content = file.read()
  457. print('encoding utf8 in opening with trafilatura did not work, trying latin1, original error message is:', e)
  458. generaltext = extract(html_content)
  459. print('generaltext word count was: ', len(generaltextlist), 'but now trafilatura did the job and new wordcount is:', len(generaltext.split(' ')))
  460. if len(generaltextlist) < 2:
  461. print('no text parsed, the wc is', len(generaltextlist))
  462. print('text under 2 words for entry id', entry_id, ' number of words:', len(generaltextlist))
  463. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  464. try:
  465. with open(file_name , 'r', encoding='utf-8') as file:
  466. html_content = file.read()
  467. except Exception as e:
  468. with open(file_name , 'r', encoding='latin-1') as file:
  469. html_content = file.read()
  470. print('encoding utf8 in opening with trafilatura did not work, trying latin1, original error message is:', e)
  471. generaltext = extract(html_content)
  472. try:
  473. if len(generaltext) > 2:
  474. print('generaltext word count was: ', len(generaltextlist), 'but now trafilatura did the job and new wordcount is:', len(generaltext.split(' ')))
  475. except:
  476. print('trafilatura got this out:', generaltext , 'setting generaltext to NONE')
  477. generaltext = 'NONE'
  478. dictionary_entry_list[entry_id]["text"] = generaltext
  479. dictionary_entry_list[entry_id]["text-word-count"] = len(generaltextlist)
  480. f = open("spiders/output/" + fdb + str(i) + "entryList.txt", "w+")
  481. f.write(str(dictionary_entry_list))
  482. f.close