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.

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