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.

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