Java Examples - Web Page Scraping
The following example demonstrates how to use the URL() constructor of the net.URL class to fetch a web page:
Main.java File
import
java
.
io
.
BufferedReader
;
import
java
.
io
.
BufferedWriter
;
import
java
.
io
.
FileWriter
;
import
java
.
io
.
InputStreamReader
;
import
java
.
net
.
URL
;
public
class
Main
{
public
static
void
main
(
String
[
]
args
)
throws
Exception
{
URL
url
=
new
URL
(
"
http://www.runoob.com
"
)
;
BufferedReader
reader
=
new
BufferedReader
(
new
InputStreamReader
(
url
.
openStream
(
)
)
)
;
BufferedWriter
writer
=
new
BufferedWriter
(
new
FileWriter
(
"
data.html
"
)
)
;
String
line
;
while
(
(
line
=
reader
.
readLine
(
)
)
!=
null
)
{
System
.
out
.
println
(
line
)
;
writer
.
write
(
line
)
;
writer
.
newLine
(
)
;
}
reader
.
close
(
)
;
writer
.
close
(
)
;
}
}
The output of the above code is (the web page source code, stored in the data.html file in the current directory):
……
Java Examples