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.

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