Repository navigation
Expand file tree
/
Copy pathElPaisScraper.java
More file actions
188 lines (149 loc) · 6.74 KB
/
Copy pathElPaisScraper.java
File metadata and controls
188 lines (149 loc) · 6.74 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package com.akshay;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
public class ElPaisScraper {
public static void analyzeRepeatedWords(List<String> titles) {
Map<String, Integer> wordCount = new HashMap<>();
for (String title : titles) {
String[] words = title.toLowerCase().replaceAll("[^a-zA-Z ]", "").split("\\s+");
for (String word : words) {
if (word.length() > 1) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
}
}
System.out.println("\n🔁 Repeated Words in Titles:");
for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {
if (entry.getValue() > 1) {
System.out.println(entry.getKey() + ": " + entry.getValue() + " times");
}
}
}
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
WebDriver driver = new ChromeDriver();
List<Article> articleList = new ArrayList<>();
try {
driver.get("https://elpais.com/");
Thread.sleep(3000);
// Accept cookie banner
try {
WebElement acceptCookies = driver.findElement(By.xpath("//button[contains(., 'Aceptar')]"));
if (acceptCookies.isDisplayed()) {
acceptCookies.click();
Thread.sleep(2000);
}
} catch (Exception e) {
System.out.println("ℹ️ No cookie banner to accept or already dismissed.");
}
// Click on Opinión section
WebElement opinionLink = driver.findElement(By.xpath("//a[contains(@href,'/opinion/') and text()='Opinión']"));
((JavascriptExecutor) driver).executeScript("arguments[0].click();", opinionLink); // ✅ JavaScript click
Thread.sleep(3000);
// Get top 5 article URLs
List<WebElement> articles = driver.findElements(By.cssSelector("article a"));
List<String> articleLinks = new ArrayList<>();
List<String> translatedTitles = new ArrayList<>();
for (WebElement a : articles) {
String link = a.getAttribute("href");
if (link != null && link.contains("/opinion/") && !articleLinks.contains(link)) {
articleLinks.add(link);
}
if (articleLinks.size() == 5) break;
}
// Visit each article
for (String url : articleLinks) {
driver.get(url);
Thread.sleep(3000);
String title = "(No title found)";
String content;
String imageUrl;
try {
// Extract title
WebElement titleEl = driver.findElement(By.tagName("h1"));
title = titleEl.getText();
} catch (Exception e) {
title = "(No title found)";
}
String translatedTitle = LibreTranslateUtil.translateWithMyMemory(title, "es", "en");
System.out.println("🔤 Translated Title: " + translatedTitle);
translatedTitles.add(translatedTitle);
try {
List<WebElement> paragraphs = driver.findElements(By.cssSelector(
"div[data-dtm-region='articulo_cuerpo'] p, div[data-test='article-body'] p"
));
StringBuilder contentBuilder = new StringBuilder();
for (WebElement p : paragraphs) {
String para = p.getText().trim();
if (!para.isEmpty()) {
contentBuilder.append(para).append("\n");
}
}
content = contentBuilder.toString().trim();
} catch (Exception e) {
content = "(No content found)";
}
try {
// Extract cover image
WebElement imageEl = driver.findElement(By.cssSelector("figure img"));
imageUrl = imageEl.getAttribute("src");
// Download image
if (imageUrl != null && !imageUrl.isEmpty()) {
saveImage(imageUrl, title.replaceAll("[^a-zA-Z0-9]", "_") + ".jpg");
}
} catch (Exception e) {
imageUrl = "(No image found)";
}
articleList.add(new Article(title, content, imageUrl));
}
// Print final result
System.out.println("\n🧾 Article Details:");
for (Article a : articleList) {
System.out.println("\n=========================");
System.out.println("Title: " + a.title);
System.out.println("Image: " + a.imageUrl);
System.out.println("Content:\n" + a.content);
}
// Analyze repeated words in translated titles
analyzeRepeatedWords(translatedTitles);
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.quit();
}
}
// Helper to save image
public static void saveImage(String imageUrl, String fileName) {
try {
File dir = new File("images");
if (!dir.exists()) dir.mkdir();
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.connect();
try (InputStream in = connection.getInputStream();
FileOutputStream out = new FileOutputStream("images/" + fileName)) {
byte[] buffer = new byte[2048];
int length;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
}
System.out.println("🖼️ Image saved: " + fileName);
} catch (IOException e) {
System.out.println("⚠️ Failed to download image: " + imageUrl);
}
}
}