【发布时间】:2019-12-23 18:03:59
【问题描述】:
出于教育目的,我很想抓取前 250 部电影 (https://www.imdb.com/chart/top/) 的标题。
我尝试了很多东西,但每次都搞砸了。你能帮我用Java和正则表达式刮掉标题吗?
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class scraping {
public static void main (String args[]) {
try {
URL URL1=new URL("https://www.imdb.com/chart/top/");
URLConnection URL1c=URL1.openConnection();
BufferedReader br=new BufferedReader(new
InputStreamReader(URL1c.getInputStream(),"ISO8859_7"));
String line;int lineCount=0;
Pattern pattern = Pattern.compile("<td\\s+class=\"titleColumn\"[^>]*>"+ ".*?</a>");
Matcher matcher = pattern.matcher(br.readLine());
while(matcher.find()){
System.out.println(matcher.group());
}
} catch (Exception e) {
System.out.println("Exception: " + e.getClass() + ", Details: " + e.getMessage());
}
}
}
感谢您的宝贵时间。
【问题讨论】:
-
使用 Jsoup,你的生活应该会变得更轻松。
-
你可以使用 selenium 和 scape xml
-
你的 readLine 现在只返回一个空字符串^^
-
@azro 你能帮我吗?因为经过这么多次尝试,我的大脑会在这个时候爆炸。如何打印 td class=titleColumn 的内容?
-
看看regex101.com/r/XfiaB7/1,如果你坚持让它在正则表达式中工作
标签: java regex web-scraping screen-scraping