-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_text_extractors.py
More file actions
103 lines (74 loc) · 2.32 KB
/
Copy pathweb_text_extractors.py
File metadata and controls
103 lines (74 loc) · 2.32 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import requests
from utils import link_preprocessing_urlparse
def extract_text_bs4(url):
"""
Extracts full raw text from a webpage using BeautifulSoup.
Args:
url (str): The URL of the webpage.
Returns:
str: Extracted plain text.
"""
from bs4 import BeautifulSoup
text = ''
response = requests.get(url)
soup = BeautifulSoup(response.text, features="html.parser")
# Extracts all visible text, separating elements by space
text = soup.get_text(separator=' ')
return text
def extract_text_rlxml(url):
"""
Extracts the title and main content from a webpage using the Readability algorithm.
Args:
url (str): The URL of the webpage.
Returns:
str: Concatenation of title and main content HTML.
"""
from readability import Document
text = ''
response = requests.get(url)
doc = Document(response.text)
title = doc.title()
content = doc.summary()
# Combine title and content
text = title + '\n\n' + content
return text
def extract_text_gs3(url):
"""
Extracts the title and cleaned article text using Goose3.
Args:
url (str): The URL of the webpage.
Returns:
str: Concatenation of article title and cleaned body text.
"""
from goose3 import Goose
text = ''
g = Goose()
article = g.extract(url=url)
# Combine title and cleaned text
text = article.title + "\n\n" + article.cleaned_text
return text
def extract_text_trafilatura(url):
"""
Extracts cleaned article text using Trafilatura.
Args:
url (str): The URL of the webpage.
Returns:
str: Cleaned main text of the article.
"""
import trafilatura
text = ''
response = requests.get(url)
# Extract relevant content
text = trafilatura.extract(response, include_comments=False, include_tables=False)
return text
def extract_text(url, extraction_method):
if extraction_method == 'bs4':
return extract_text_bs4(url)
elif extraction_method == 'rlxml':
return extract_text_rlxml(url)
elif extraction_method == 'gs3':
return extract_text_gs3(url)
elif extraction_method == 'trafilatura':
return extract_text_trafilatura(url)
else:
raise ValueError(f"Unsupported extraction method: {extraction_method}")