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.

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