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.

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