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.

951 lines
47 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. import time
  14. import subprocess
  15. class fdb_spider(object):
  16. def __init__(self, config_file):
  17. with open(config_file, "r") as stream:
  18. try:
  19. self.config = yaml.safe_load(stream)
  20. except yaml.YAMLError as exc:
  21. print(exc)
  22. # input list of funding databases in form of yaml file ['foerderinfo.bund.de', 'ausschreibungen.giz.de', .. , 'usw']
  23. def download_entry_list_pages_of_funding_databases(self, list_of_fdbs):
  24. # download only html pages of the funding databases specified in input
  25. for fdb in list_of_fdbs:
  26. for key in self.config:
  27. if key in list_of_fdbs:
  28. try:
  29. entry_list = self.config.get(key).get("entry-list")
  30. except Exception as e:
  31. print(
  32. "There is a problem with the configuration variable entryList in the config.yaml - the original error message is:",
  33. e,
  34. )
  35. try:
  36. entry_list_link1 = entry_list.get("link1")
  37. except Exception as e:
  38. print(
  39. "No link1 defined in config.yaml - the original error message is:",
  40. e,
  41. )
  42. try:
  43. entry_list_link2 = entry_list.get("link2")
  44. except Exception as e:
  45. print(
  46. "No link2 defined in config.yaml - the original error message is:",
  47. e,
  48. )
  49. try:
  50. entry_list_jslink1 = entry_list.get("jslink1")
  51. except Exception as e:
  52. print(
  53. "No jslink1 defined in config.yaml - the original error message is:",
  54. e,
  55. )
  56. entry_list_jslink1 = 'NONE'
  57. try:
  58. entry_list_jslink2 = entry_list.get("jslink2")
  59. except Exception as e:
  60. print(
  61. "No jslink2 defined in config.yaml - the original error message is:",
  62. e,
  63. )
  64. entry_list_jslink2 = 'NONE'
  65. try:
  66. entry_iteration_var_list = eval(entry_list.get("iteration-var-list"))
  67. except Exception as e:
  68. print(
  69. "No iteration-var-list defined in config.yaml - the original error message is:",
  70. e,
  71. )
  72. try:
  73. entry_jsiteration_var_list = eval(entry_list.get("jsiteration-var-list"))
  74. except Exception as e:
  75. print(
  76. "No jsiteration-var-list defined in config.yaml - the original error message is:",
  77. e,
  78. )
  79. try:
  80. entry_jsdomain = entry_list.get("jsdomain")
  81. except Exception as e:
  82. print(
  83. "No jsdomain defined in config.yaml - the original error message is:",
  84. e,
  85. )
  86. entry_jsdomain = 'NONE'
  87. if entry_jsdomain == 'NONE' or entry_jsdomain == 'None':
  88. for i in entry_iteration_var_list:
  89. # download the html page of the List of entrys
  90. response = urllib.request.urlopen(entry_list_link1 + str(i) + entry_list_link2)
  91. # web_content = response.read().decode("UTF-8")
  92. try:
  93. web_content = response.read().decode("UTF-8")
  94. except Exception as e:
  95. try:
  96. web_content = response.read().decode("latin-1")
  97. print(
  98. "decoding the respone in utf8 did not work, try to decode latin1 now - the original error message is:",
  99. e,
  100. )
  101. except Exception as ex:
  102. print(ex)
  103. # save interim results to files
  104. if (len(web_content)) < 10:
  105. print('getting the html page through urllib did not work, trying with requests librarys function get')
  106. try:
  107. res = requests.get(entry_list_link1 + str(i) + entry_list_link2)
  108. web_content = res.text
  109. except Exception as e:
  110. print('also requests library did not work, original error is:', e)
  111. # print(web_content)
  112. f = open("spiders/pages/" + key + str(i) + "entryList.html", "w+")
  113. f.write(web_content)
  114. f.close
  115. else:
  116. from selenium import webdriver
  117. from selenium.webdriver.chrome.service import Service
  118. #from selenium.webdriver.common.action_chains import ActionChains
  119. from pyvirtualdisplay import Display
  120. # changed display to 1200, because element was not found in "mobile version" with 800 width
  121. display = Display(visible=0, size=(1200, 800))
  122. display.start()
  123. ##outputdir = '.'
  124. ##service_log_path = "{}/chromedriver.log".format(outputdir)
  125. ##service_args = ['--verbose']
  126. ##driver = webdriver.Chrome('/usr/bin/chromium')
  127. options = webdriver.ChromeOptions()
  128. #options.add_argument('headless')
  129. options.add_argument("--remote-debugging-port=9222")
  130. options.add_argument('--no-sandbox')
  131. options.add_argument('--disable-dev-shm-usage')
  132. service = Service(executable_path='/usr/bin/chromedriver')
  133. driver = webdriver.Chrome(options=options, service=service)
  134. # driver = webdriver.Chrome()
  135. driver.implicitly_wait(5)
  136. driver.get(entry_jsdomain)
  137. for i in range(len(entry_jsiteration_var_list)):
  138. time.sleep(1)
  139. print('trying to get element')
  140. try:
  141. # scroll down, to get the javascript view loading to get the elements
  142. driver.execute_script("scroll(0, 600)")
  143. element = driver.find_element(
  144. "xpath",
  145. entry_list_jslink1
  146. + str(entry_jsiteration_var_list[i])
  147. + entry_list_jslink2
  148. )
  149. print(entry_iteration_var_list[i])
  150. time.sleep(1)
  151. print('scrolling..')
  152. # scroll into view, because otherwise with javascript generated elements
  153. # it can be that clicking returns an error
  154. driver.execute_script("arguments[0].scrollIntoView();", element)
  155. print('clicking..')
  156. time.sleep(1)
  157. element.click()
  158. time.sleep(1)
  159. #window_after = driver.window_handles[1]
  160. print('length of the window handles', len(driver.window_handles))
  161. #driver.switch_to.window(window_after)
  162. web_content = driver.page_source
  163. f = open("spiders/pages/" + key + str(entry_iteration_var_list[i]) + "entryList.html", "w+")
  164. f.write(web_content)
  165. f.close
  166. except Exception as e:
  167. print('the iteration var element for clicking the pages was not found.. the original message is:',e )
  168. def find_config_parameter(self, list_of_fdbs):
  169. for fdb in list_of_fdbs:
  170. try:
  171. iteration_var_list = eval(self.config.get(fdb).get("entry-list").get("iteration-var-list"))
  172. except Exception as e:
  173. print(
  174. "There is a problem with the configuration variable entryList iteration var list in the config.yaml",
  175. e,
  176. )
  177. fdb_conf = self.config.get(fdb)
  178. fdb_domain = fdb_conf.get("domain")
  179. fdb_conf_entry_list = fdb_conf.get("entry-list")
  180. fdb_conf_entry_list_parent = fdb_conf_entry_list.get("parent")
  181. fdb_conf_entry_list_child_name = fdb_conf_entry_list.get("child-name")
  182. fdb_conf_entry_list_child_link = fdb_conf_entry_list.get("child-link")
  183. fdb_conf_entry_list_child_info = fdb_conf_entry_list.get("child-info")
  184. fdb_conf_entry_list_child_period = fdb_conf_entry_list.get("child-period")
  185. for i in iteration_var_list:
  186. print(i)
  187. try:
  188. # use soupparser to handle broken html
  189. tree = lxml.html.soupparser.parse(
  190. "spiders/pages/" + fdb + str(i) + "entryList.html"
  191. )
  192. except Exception as e:
  193. tree = html.parse("spiders/pages/" + fdb + str(i) + "entryList.html")
  194. print(
  195. "parsing the xml files did not work with the soupparser. Broken html will not be fixed as it could have been",
  196. e,
  197. )
  198. try:
  199. print('this is the n looped elements of the parent specified in config.yaml:')
  200. #print('entrylistparent', fdb_conf_entry_list_parent)
  201. #print(tree.xpath("//html//body//div//main//div//div[@class='row']//section[@class='l-search-result-list']"))
  202. #print(etree.tostring(tree.xpath(fdb_conf_entry_list_parent)).decode())
  203. for n in range(len(tree.xpath(fdb_conf_entry_list_parent))):
  204. print('-----------------------------------------------------------------------------------------------------------------------------------------')
  205. print(etree.tostring(tree.xpath(fdb_conf_entry_list_parent)[n]).decode())
  206. print('this is the name children:')
  207. name_element = tree.xpath(fdb_conf_entry_list_parent + fdb_conf_entry_list_child_name)
  208. print(name_element)
  209. #for name in name_element:
  210. # print(name)
  211. print(len(name_element))
  212. print('this is the link children:')
  213. link_element = tree.xpath(fdb_conf_entry_list_parent + fdb_conf_entry_list_child_link)
  214. print(link_element)
  215. #for link in link_element:
  216. # print(link)
  217. print(len(link_element))
  218. print('this is the info children:')
  219. info_element = tree.xpath(fdb_conf_entry_list_parent + fdb_conf_entry_list_child_info)
  220. print(info_element)
  221. print(len(info_element))
  222. print('this is the period children:')
  223. period_element = tree.xpath(fdb_conf_entry_list_parent + fdb_conf_entry_list_child_period)
  224. print(period_element)
  225. print(len(period_element))
  226. except Exception as e:
  227. print(
  228. "parsing the html did not work.",
  229. e,
  230. )
  231. def parse_entry_list_data2dictionary(self, list_of_fdbs):
  232. for fdb in list_of_fdbs:
  233. try:
  234. iteration_var_list = eval(self.config.get(fdb).get("entry-list").get("iteration-var-list"))
  235. except Exception as e:
  236. print(
  237. "There is a problem with the configuration variable entryList iteration var list in the config.yaml - the original error message is:",
  238. e,
  239. )
  240. for i in iteration_var_list:
  241. print(i)
  242. try:
  243. # use soupparser to handle broken html
  244. tree = lxml.html.soupparser.parse(
  245. "spiders/pages/" + fdb + str(i) + "entryList.html"
  246. )
  247. except Exception as e:
  248. tree = html.parse("spiders/pages/" + fdb + str(i) + "entryList.html")
  249. print(
  250. "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:",
  251. e,
  252. )
  253. try:
  254. #print('this is the n looped elements of the parent specified in config.yaml:')
  255. #for e in tree.iter():
  256. # print(e.tag)
  257. #
  258. #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()]"):
  259. #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']"):
  260. # print(etree.tostring(e).decode())
  261. dictionary_entry_list = {}
  262. fdb_conf = self.config.get(fdb)
  263. fdb_domain = fdb_conf.get("domain")
  264. fdb_conf_entry_list = fdb_conf.get("entry-list")
  265. fdb_conf_entry_list_parent = fdb_conf_entry_list.get("parent")
  266. fdb_conf_entry_list_child_name = fdb_conf_entry_list.get("child-name")
  267. fdb_conf_entry_list_child_link = fdb_conf_entry_list.get("child-link")
  268. fdb_conf_entry_list_child_info = fdb_conf_entry_list.get("child-info")
  269. fdb_conf_entry_list_child_period = fdb_conf_entry_list.get("child-period")
  270. #print('blabliblub')
  271. #print('len', len(tree.xpath(fdb_conf_entry_list_parent)))
  272. for n in range(len(tree.xpath(fdb_conf_entry_list_parent))):
  273. try:
  274. name = tree.xpath(
  275. fdb_conf_entry_list_parent
  276. + "["
  277. + str(n+1)
  278. + "]"
  279. + fdb_conf_entry_list_child_name
  280. )[0]
  281. except Exception as e:
  282. print("name could not be parsed", e)
  283. name = 'NONE'
  284. try:
  285. info = tree.xpath(
  286. fdb_conf_entry_list_parent
  287. + "["
  288. + str(n+1)
  289. + "]"
  290. + fdb_conf_entry_list_child_info
  291. )[0]
  292. except Exception as e:
  293. print("info could not be parsed", e, info)
  294. info = 'NONE'
  295. try:
  296. period = tree.xpath(
  297. fdb_conf_entry_list_parent
  298. + "["
  299. + str(n+1)
  300. + "]"
  301. + fdb_conf_entry_list_child_period
  302. )[0]
  303. #print('period', period)
  304. except Exception as e:
  305. print("period could not be parsed", e, period)
  306. period = 'NONE'
  307. try:
  308. link = tree.xpath(
  309. fdb_conf_entry_list_parent
  310. + "["
  311. + str(n+1)
  312. + "]"
  313. + fdb_conf_entry_list_child_link
  314. )[0]
  315. if 'javascript:' in link:
  316. #from selenium import webdriver
  317. print('link is javascript element, not url to parse')
  318. #url = 'https://example.com'
  319. #driver = webdriver.Chrome()
  320. #driver.get(url)
  321. #links = [link.get_attribute('href') for link in driver.find_elements_by_tag_name('a')]
  322. #print('link', link)
  323. except Exception as e:
  324. print("link could not be parsed", e, link)
  325. link = 'NONE'
  326. if len(name) > 0 and name != 'NONE':
  327. dictionary_entry_list[n] = {}
  328. dictionary_entry_list[n]["name"] = name
  329. dictionary_entry_list[n]["info"] = info
  330. dictionary_entry_list[n]["period"] = period
  331. print('linklink', link, fdb_domain)
  332. if fdb_domain in link:
  333. print('oi')
  334. dictionary_entry_list[n]["link"] = link
  335. if fdb_domain not in link and 'http:' in link:
  336. print('oiA')
  337. dictionary_entry_list[n]["link"] = link
  338. if fdb_domain not in link and 'www.' in link:
  339. dictionary_entry_list[n]["link"] = link
  340. if fdb_domain not in link and 'https:' in link:
  341. dictionary_entry_list[n]["link"] = link
  342. if 'javascript:' in link:
  343. dictionary_entry_list[n]["link"] = link
  344. if fdb_domain not in link:
  345. if 'http' not in link:
  346. if 'www' not in link:
  347. print('oiB')
  348. if link[0] == '/':
  349. if fdb_domain[-1] != '/':
  350. dictionary_entry_list[n]["link"] = fdb_domain + link
  351. #print('got into D', dictionary_entry_list[n]["link"])
  352. if fdb_domain[-1] == '/':
  353. dictionary_entry_list[n]["link"] = fdb_domain + link[1:]
  354. #print('got into C', dictionary_entry_list[n]["link"])
  355. if link[0] == '.' and link[1] == '/':
  356. if fdb_domain[-1] != '/':
  357. dictionary_entry_list[n]["link"] = fdb_domain + link[1:]
  358. print('got into B', dictionary_entry_list[n]["link"])
  359. if fdb_domain[-1] == '/':
  360. dictionary_entry_list[n]["link"] = fdb_domain + link[2:]
  361. print('got into A', dictionary_entry_list[n]["link"])
  362. if link[0] != '/' and link[0] != '.':
  363. dictionary_entry_list[n]["link"] = fdb_domain + '/' + link
  364. #print('got into last else', dictionary_entry_list[n]["link"])
  365. except Exception as e:
  366. print(
  367. "parsing the html did not work. Possibly you first have to run download_link_list_pages_of_funding_databases(). The original error message is:",
  368. e,
  369. )
  370. # save interim results to files
  371. f = open("spiders/output/" + fdb + str(i) + "entryList.txt", "w+")
  372. f.write(str(dictionary_entry_list))
  373. f.close
  374. def download_entry_data_htmls(self, list_of_fdbs):
  375. from selenium import webdriver
  376. from selenium.webdriver.chrome.service import Service
  377. from pyvirtualdisplay import Display
  378. display = Display(visible=0, size=(800, 800))
  379. display.start()
  380. #outputdir = '.'
  381. #service_log_path = "{}/chromedriver.log".format(outputdir)
  382. #service_args = ['--verbose']
  383. #driver = webdriver.Chrome('/usr/bin/chromium')
  384. options = webdriver.ChromeOptions()
  385. options.add_argument('headless')
  386. options.add_argument("--remote-debugging-port=9222")
  387. options.add_argument('--no-sandbox')
  388. options.add_argument('--disable-dev-shm-usage')
  389. service = Service(executable_path='/usr/bin/chromedriver')
  390. driver = webdriver.Chrome(options=options, service=service)
  391. driver.implicitly_wait(10)
  392. #driver = webdriver.Chrome()
  393. for fdb in list_of_fdbs:
  394. print('spidering ' + fdb + ' ..')
  395. try:
  396. iteration_var_list = eval(self.config.get(fdb).get("entry-list").get("iteration-var-list"))
  397. except Exception as e:
  398. print(
  399. "There is a problem with the configuration variable entryList iteration var list in the config.yaml - the original error message is:",
  400. e,
  401. )
  402. print('starting to download the entry html pages..')
  403. for i in iteration_var_list:
  404. print(i)
  405. f = open("spiders/output/" + fdb + str(i) + "entryList.txt")
  406. text = f.read()
  407. dictionary_entry_list = eval(text)
  408. fdb_conf = self.config.get(fdb)
  409. fdb_domain = fdb_conf.get("domain")
  410. fdb_conf_entry_list = fdb_conf.get("entry-list")
  411. fdb_conf_entry_list_parent = fdb_conf_entry_list.get("parent")
  412. fdb_conf_entry_list_child_name = fdb_conf_entry_list.get("child-name")
  413. try:
  414. fdb_conf_entry_list_javascript_link = fdb_conf_entry_list.get("javascript-link")
  415. except Exception as e:
  416. fdb_conf_entry_list_javascript_link = 'NONE'
  417. print('the javascript link in the config is missing, original error message is:', e)
  418. try:
  419. fdb_conf_entry_list_slow_downloading = fdb_conf_entry_list.get("slow-downloading")
  420. except Exception as e:
  421. print('the slow-downloading parameter is not set, original error message is:', e)
  422. fdb_conf_entry_list_link1 = fdb_conf_entry_list.get("link1")
  423. fdb_conf_entry_list_link2 = fdb_conf_entry_list.get("link2")
  424. if fdb_conf_entry_list_slow_downloading == 'FALSE':
  425. driver.get(fdb_conf_entry_list_link1 + str(i) + fdb_conf_entry_list_link2)
  426. else:
  427. pass
  428. for entry_id in dictionary_entry_list:
  429. print(entry_id)
  430. entry_link = dictionary_entry_list[entry_id]["link"]
  431. web_content = 'NONE'
  432. # download the html page of the entry
  433. print(entry_link)
  434. if 'javascript' in entry_link or fdb_conf_entry_list_javascript_link != 'NONE':
  435. print('oioioi',fdb_conf_entry_list_parent, entry_id, fdb_conf_entry_list_javascript_link)
  436. element = driver.find_element(
  437. "xpath",
  438. fdb_conf_entry_list_parent
  439. + "["
  440. + str(entry_id+1)
  441. + "]"
  442. + fdb_conf_entry_list_javascript_link
  443. )
  444. # to time.sleep was suggested for errors
  445. import time
  446. time.sleep(1)
  447. element.click()
  448. window_after = driver.window_handles[1]
  449. driver.switch_to.window(window_after)
  450. #element = driver.find_element("xpath", "//html")
  451. #web_content = element.text
  452. #entry_domain = driver.getCurrentUrl()
  453. entry_domain = driver.current_url
  454. dictionary_entry_list[entry_id]["domain"] = entry_domain
  455. web_content = driver.page_source
  456. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  457. os.makedirs(os.path.dirname(file_name), exist_ok=True)
  458. f = open(file_name, "w+")
  459. f.write(web_content)
  460. f.close
  461. window_before = driver.window_handles[0]
  462. driver.switch_to.window(window_before)
  463. if 'javascript' not in entry_link and '.pdf' not in entry_link and fdb_conf_entry_list_javascript_link == 'NONE':
  464. print('blabuuuuuba')
  465. #print('oi')
  466. if fdb_conf_entry_list_slow_downloading == 'TRUE':
  467. try:
  468. print("trying to get slowly entry link " , entry_link)
  469. driver.get(entry_link)
  470. time.sleep(3)
  471. web_content = driver.page_source
  472. except Exception as e:
  473. print("getting the html behind the entry link did not work, ori message is:", e)
  474. else:
  475. try:
  476. # defining cookie to not end up in endless loop because of cookie banners pointing to redirects
  477. url = entry_link
  478. req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0', 'Cookie':'myCookie=oioioioi'})
  479. response = urllib.request.urlopen(req)
  480. print('response from first one', response)
  481. except Exception as e:
  482. print('cookie giving then downloading did not work, original error is:', e)
  483. try:
  484. response = urllib.request.urlopen(entry_link.encode('ascii', errors='xmlcharrefreplace').decode('ascii'))
  485. print(
  486. "opening the link did not work, try to encode to ascii replacing xmlcharrefs now and reopen - the original error message is:",
  487. e,
  488. )
  489. except Exception as ex:
  490. print(entry_link, entry_link.encode('ascii', errors='xmlcharrefreplace').decode('ascii'), ex )
  491. try:
  492. web_content = response.read().decode("UTF-8")
  493. except Exception as e:
  494. try:
  495. web_content = response.read().decode("latin-1")
  496. print(
  497. "decoding the respone in utf8 did not work, try to decode latin1 now - the original error message is:",
  498. e,
  499. )
  500. except Exception as ex:
  501. print(ex)
  502. # save interim results to files
  503. if '.pdf' in entry_link and fdb_conf_entry_list_javascript_link == 'NONE':
  504. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  505. response = requests.get(entry_link)
  506. os.makedirs(os.path.dirname(file_name), exist_ok=True)
  507. f = open(file_name, "bw")
  508. f.write(response.content)
  509. f.close
  510. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  511. wget_wrote = False
  512. if web_content == 'NONE':
  513. print('other downloading approaches did not work, trying requests')
  514. try:
  515. from requests_html import HTMLSession
  516. session = HTMLSession()
  517. r = session.get(entry_link)
  518. r.html.render()
  519. web_content = r.text
  520. except Exception as e:
  521. print('requests_html HTMLSession did not work trying wget, ori error is:', e)
  522. try:
  523. os.makedirs(os.path.dirname(file_name), exist_ok=True)
  524. oi = subprocess.run(["wget", entry_link, '--output-document=' + file_name])
  525. wget_wrote = True
  526. except subprocess.CalledProcessError:
  527. print('wget downloading did not work.. saving NONE to file now')
  528. if wget_wrote == False:
  529. os.makedirs(os.path.dirname(file_name), exist_ok=True)
  530. f = open(file_name, "w+")
  531. f.write(web_content)
  532. f.close
  533. # save the entry_domain, implemented first for further downloads in javascript links
  534. f = open("spiders/output/" + fdb + str(i) + "entryList.txt", "w+")
  535. f.write(str(dictionary_entry_list))
  536. f.close
  537. def parse_entry_data2dictionary(self, list_of_fdbs):
  538. for fdb in list_of_fdbs:
  539. try:
  540. fdb_config = self.config.get(fdb)
  541. print('oi oi',fdb_config)
  542. fdb_config_entrylist = fdb_config.get("entry-list")
  543. iteration_var_list = eval(fdb_config_entrylist.get("iteration-var-list"))
  544. except Exception as e:
  545. print(
  546. "There is a problem with the configuration variable entryList iteration var list in the config.yaml - the original error message is:",
  547. e,
  548. )
  549. for i in iteration_var_list:
  550. print("started to parse data of entry of " + fdb + " ..")
  551. f = open("spiders/output/" + fdb + str(i) + "entryList.txt")
  552. text = f.read()
  553. dictionary_entry_list = eval(text)
  554. fdb_conf = self.config.get(fdb)
  555. fdb_domain = fdb_conf.get("domain")
  556. fdb_conf_entry = fdb_conf.get("entry")
  557. #print('balubaluba', fdb_conf_entry)
  558. fdb_conf_entry_general = fdb_conf_entry.get("general")
  559. #print(fdb_conf_entry_general)
  560. for entry_id in dictionary_entry_list:
  561. print(
  562. "started to parse data of entry with name "
  563. + dictionary_entry_list[entry_id]["name"]
  564. + " .."
  565. )
  566. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  567. try:
  568. tree = lxml.html.soupparser.parse(file_name)
  569. except Exception as e:
  570. tree = html.parse(file_name)
  571. print(
  572. "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:",
  573. e,
  574. )
  575. if fdb_conf_entry_general["uniform"] == 'TRUE':
  576. fdb_conf_entry_unitrue = fdb_conf_entry.get("unitrue")
  577. for key in fdb_conf_entry_unitrue:
  578. fdb_conf_entry_unitrue_child = fdb_conf_entry_unitrue.get(key)
  579. print('unitrue_child',fdb_conf_entry_unitrue_child)
  580. try:
  581. child = tree.xpath(
  582. fdb_conf_entry_unitrue_child
  583. )[0]
  584. print('oi', child)
  585. except:
  586. print('getting unitruechild did not work')
  587. child = 'NONE'
  588. print("oi", child)
  589. if '.pdf' in child:
  590. print('child in entry data is pdf, downloading it..')
  591. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".pdf"
  592. entry_link = dictionary_entry_list[entry_id]["link"]
  593. print('that is the child: ' + child)
  594. if 'http' in child:
  595. try:
  596. response = requests.get(child)
  597. except Exception as e:
  598. print(child + ' does not appear to be valid pdf link to download, original message is ' + e)
  599. if 'http' not in child:
  600. if 'javascript' or 'js' not in entry_link and 'http' in entry_link:
  601. try:
  602. response = requests.get(entry_link + child)
  603. except Exception as e:
  604. print(entry_link + child + ' seems not a valid pdf link to download, orginal error message is:', e)
  605. if 'javascript' or 'js' in entry_link:
  606. entry_domain = dictionary_entry_list[entry_id]["domain"]
  607. if child[0] == '.' and child[1] == '/':
  608. if entry_domain[-1] == '/':
  609. pdf_link = entry_domain[:-1] + child[1:]
  610. if entry_domain[-1] != '/':
  611. #print('it got into OIOIOIOOIOI')
  612. #print('before loop ', entry_domain)
  613. cut_value = 0
  614. for n in range(len(entry_domain)):
  615. if entry_domain[-n] != '/':
  616. cut_value += 1
  617. else:
  618. break
  619. entry_domain = entry_domain[:-cut_value]
  620. #print('after loop ', entry_domain)
  621. pdf_link = entry_domain + child[1:]
  622. #print('the pdf link after recursive until slash: ', pdf_link)
  623. if child[0] == '/':
  624. if entry_domain[-1] == '/':
  625. pdf_link = entry_domain[:-1] + child
  626. if entry_domain[-1] != '/':
  627. pdf_link = entry_domain + child
  628. print('pdf_link', pdf_link)
  629. try:
  630. response = requests.get(pdf_link)
  631. except Exception as e:
  632. print(pdf_link + ' seems not a valid pdf link to download, orginal error message is:', e)
  633. #response = requests.get(child)
  634. os.makedirs(os.path.dirname(file_name), exist_ok=True)
  635. f = open(file_name, "bw")
  636. f.write(response.content)
  637. f.close
  638. print('parsing a pdf', pdf_link, entry_id)
  639. try:
  640. generaltext = ''
  641. for page_layout in extract_pages(file_name):
  642. for element in page_layout:
  643. if isinstance(element, LTTextContainer):
  644. generaltext += element.get_text()
  645. except Exception as e:
  646. generaltext = 'NONE'
  647. print('parsing pdf did not work, the original error is:', e )
  648. dictionary_entry_list[entry_id][key] = generaltext
  649. if len(child) > 0 and '.pdf' not in child:
  650. dictionary_entry_list[entry_id][key] = child[
  651. 0
  652. ]
  653. else:
  654. fdb_conf_entry_unifalse = fdb_conf_entry.get("unifalse")
  655. fdb_conf_entry_unifalse_wordlist = fdb_conf_entry_unifalse.get("wordlist")
  656. if '.pdf' in dictionary_entry_list[entry_id]["link"]:
  657. print('parsing a pdf', dictionary_entry_list[entry_id]["link"], entry_id)
  658. try:
  659. generaltext = ''
  660. for page_layout in extract_pages(file_name):
  661. for element in page_layout:
  662. if isinstance(element, LTTextContainer):
  663. generaltext += element.get_text()
  664. except Exception as e:
  665. generaltext = 'NONE'
  666. print('parsing pdf did not work, the original error is:', e )
  667. else:
  668. p_text = tree.xpath(
  669. "//p//text()"
  670. )
  671. div_text = tree.xpath(
  672. "//div//text()"
  673. )
  674. #print("oi", text)
  675. generaltext = ''
  676. for n in range(len(p_text)):
  677. if len(p_text[n]) > 0:
  678. generaltext += p_text[n] + ' '
  679. for n in range(len(div_text)):
  680. if len(div_text[n]) > 0 and div_text[n] not in p_text:
  681. generaltext += div_text[n] + ' '
  682. generaltextlist = generaltext.split(' ')
  683. if len(generaltextlist) > 5000:
  684. print('text over 1000 words for entry id', entry_id, ' number of words:', len(generaltextlist))
  685. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  686. try:
  687. with open(file_name , 'r', encoding='utf-8') as file:
  688. html_content = file.read()
  689. except Exception as e:
  690. with open(file_name , 'r', encoding='latin-1') as file:
  691. html_content = file.read()
  692. print('encoding utf8 in opening with trafilatura did not work, trying latin1, original error message is:', e)
  693. generaltext = extract(html_content)
  694. print('generaltext word count was: ', len(generaltextlist), 'but now trafilatura did the job and new wordcount is:', len(generaltext.split(' ')))
  695. if len(generaltextlist) < 2:
  696. print('no text parsed, the wc is', len(generaltextlist))
  697. print('text under 2 words for entry id', entry_id, ' number of words:', len(generaltextlist))
  698. file_name = "spiders/pages/" + fdb + str(i) + "/" + str(entry_id) + ".html"
  699. try:
  700. with open(file_name , 'r', encoding='utf-8') as file:
  701. html_content = file.read()
  702. except Exception as e:
  703. with open(file_name , 'r', encoding='latin-1') as file:
  704. html_content = file.read()
  705. print('encoding utf8 in opening with trafilatura did not work, trying latin1, original error message is:', e)
  706. generaltext = extract(html_content)
  707. try:
  708. if len(generaltext) > 2:
  709. print('generaltext word count was: ', len(generaltextlist), 'but now trafilatura did the job and new wordcount is:', len(generaltext.split(' ')))
  710. except:
  711. print('trafilatura got this out:', generaltext , 'setting generaltext to NONE')
  712. generaltext = 'NONE'
  713. dictionary_entry_list[entry_id]["text"] = generaltext
  714. dictionary_entry_list[entry_id]["text-word-count"] = len(generaltextlist)
  715. f = open("spiders/output/" + fdb + str(i) + "entryList.txt", "w+")
  716. f.write(str(dictionary_entry_list))
  717. f.close