引入相关jar包
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.12.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>7.7.2</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
<version>7.7.2</version>
</dependency>
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Content {
private String title;
private String img;
private String price;
}
@Component
public class HtmlParseUtil {
public static void main(String[] args) throws IOException {
new HtmlParseUtil().parseJd("java").forEach(System.out::println);
}
public ArrayList<Content> parseJd(String keywords) throws IOException {
String url = "https://search.jd.com/Search?keyword="+keywords;
Document document = Jsoup.parse(new URL(url),30000);
Element element = document.getElementById("J_goodsList");
Elements elements = element.getElementsByTag("li");
ArrayList<Content> goodsList = new ArrayList<>();
for(Element el : elements){
String img = el.getElementsByTag("img")
.eq(0).attr("data-lazy-img");
String price = el.getElementsByClass("p-price").eq(0).text();
String title = el.getElementsByClass("p-name").eq(0).text();
Content content = new Content();
content.setTitle(title);
content.setImg(img);
content.setPrice(price);
goodsList.add(content);
}
return goodsList;
}
}
public Boolean parseContent(String keywords) throws IOException {
List<Content> contents = htmlParseUtil.parseJd(keywords);
if(contents.size()>0){
List<Document> documentList =new ArrayList<>();
for(Content content:contents){
Document document =new Document();
document.add(new TextField("title",content.getTitle(), Field.Store.YES));
document.add(new TextField("img",content.getImg(), Field.Store.YES));
document.add(new TextField("price",content.getPrice(), Field.Store.YES));
documentList.add(document);
}
Analyzer analyzer =new StandardAnalyzer();
Directory dir = FSDirectory.open(Paths.get("E:\\luceneJdDir"));
IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
IndexWriter indexWriter = new IndexWriter(dir,indexWriterConfig);
for(Document doc: documentList){
indexWriter.addDocument(doc);
}
indexWriter.close();
return true;
}
return false;
}