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.

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