-
Notifications
You must be signed in to change notification settings - Fork 0
/
soup_utils.py
executable file
·53 lines (47 loc) · 1.73 KB
/
soup_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import requests
from time import sleep
from bs4 import BeautifulSoup, Comment
from selenium import webdriver
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from concurrent.futures import ProcessPoolExecutor
import concurrent.futures
def getSoupFromURL(url, suppressOutput=True, max_retry=10):
"""
This function grabs the url and returns and returns the BeautifulSoup object
"""
options = FirefoxOptions()
options.add_argument("--headless")
browser = webdriver.Firefox(options=options)
browser.get(url)
if not suppressOutput:
print(url)
num_attempts = 0
while num_attempts < max_retry:
try:
num_attempts += 1
r = requests.get(url)
r.raise_for_status()
final = BeautifulSoup(browser.page_source, "html.parser")
browser.quit()
sleep(50)
return final
except requests.exceptions.HTTPError as http:
print("ERROR - HTTP:", http)
if http.errno == 500:
sleep(100)
except requests.exceptions.ConnectionError as connection:
print("ERROR - Connection:", connection)
return None
except requests.exceptions.Timeout as timeout:
print("ERROR - Timeout:", timeout)
except requests.exceptions.TooManyRedirects as redir:
print("ERROR - Bad URL:", redir)
return None
except requests.exceptions.RequestException as e:
print("ERROR:", e)
def find_html_in_comment(soup):
for element in soup.children:
if isinstance(element, Comment):
comment = str(element.string).strip()
return BeautifulSoup(comment, 'html5lib')
return None