2016-10-04 3 views
1

JS0p를 사용하여 Moto X 링크의 제품 리뷰를 추출하려고하는데 NullPointerException이 발생합니다. 또한, 리뷰의 "Read More"링크를 클릭 한 후 표시되는 텍스트를 추출하고 싶습니다.divs의 하위에서 텍스트를 스크랩하는 Jsoup

import java.io.*; 
import org.jsoup.*; 
import org.jsoup.nodes.*; 
import org.jsoup.select.*; 

public class JSoupEx 
{ 
    public static void main(String[] args) throws IOException 
    { 
     Document doc = Jsoup.connect("https://www.flipkart.com/moto-x-play-with-turbo-charger-white-16-gb/product-reviews/itmefzwvdejejvth?pid=MOBEFM5HAFRNSJJA").get(); 
     Element ele = doc.select("div[class=qwjRop] > div").first(); 
     System.out.println(ele.text()); 
    } 
} 

모든 솔루션?

답변

1

는 개발자 도구에서 네트워크 탭을 사용하여, 제안, 우리는 응답으로 (JSON 형식) 리뷰를 수신 요청 참조 : 우리가 추출 할 수 JSON.simple 같은 JSON 파서를 사용

https://www.flipkart.com/api/3/product/reviews?productId=MOBEFM5HAFRNSJJA&count=15&ratings=ALL&reviewerType=ALL&sortOrder=MOST_HELPFUL&start=0 

을 리뷰 작성자, 유용성 및 텍스트와 같은 정보

예 코드

String userAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"; 
String reviewApiCall = "https://www.flipkart.com/api/3/product/reviews?productId=MOBEFM5HAFRNSJJA&count=15&ratings=ALL&reviewerType=ALL&sortOrder=MOST_HELPFUL&start="; 
String xUserAgent = userAgent + " FKUA/website/41/website/Desktop"; 
String referer = "https://www.flipkart.com/moto-x-play-with-turbo-charger-white-16-gb/product-reviews/itmefzwvdejejvth?pid=MOBEFM5HAFRNSJJA"; 
String host = "www.flipkart.com"; 
int numberOfPages = 2; // first two pages of results will be fetched 

try { 
    // loop for multiple review pages 
    for (int i = 0; i < numberOfPages; i++) { 
     // query reviews 
     Response response = Jsoup.connect(reviewApiCall+(i*15)).userAgent(userAgent).referrer(referer).timeout(5000) 
       .header("x-user-agent", xUserAgent).header("host", host).ignoreContentType(true).execute(); 

     System.out.println("Response in JSON format:\n\t" + response.body() + "\n"); 

     // parse json response 
     JSONObject jsonObject = (JSONObject) new JSONParser().parse(response.body().toString()); 
     jsonObject = (JSONObject) jsonObject.get("RESPONSE"); 
     JSONArray jsonArray = (JSONArray) jsonObject.get("data"); 

     for (Object object : jsonArray) { 
      jsonObject = (JSONObject) object; 
      jsonObject = (JSONObject) jsonObject.get("value"); 
      System.out.println("Author: " + jsonObject.get("author") + "\thelpful: " 
        + jsonObject.get("helpfulCount") + "\n\t" 
        + jsonObject.get("text").toString().replace("\n", "\n\t") + "\n"); 
     } 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

출력

Response in JSON format: 
    {"CACHE_INVALIDATION_TTL":"132568825671","REQUEST":null,"REQUEST-ID": [...] } 

Author: Flipkart Customer helpful: 140 
    A great phone at an affordable price with 
    -an outstanding camera 
    -great battery life 
    -an excellent display 
    -premium looks 
    the flipkart delivery was also fast and perfect. 

Author: Vaibhav Yadav helpful: 518 
    I m writing this review after using 2 months.. 
    First of all ..I must say this is one of the best product ..camera quality is best in natural lights or daytime..but in low light and in the night..camera quality is not so good but it's ok.. 
    It has good battery backup ..last one day on 3g usage ..while using 4g ..it lasts for about 10-12 hour.. 
    Turbo charges is good..although ..my charger is not working.. 
    Only problem in this phone is ..while charging..this phone heats a lot..this may b becoz of turbo charger..if u r using other charger than it does not heat.. 

Author: KAPIL CHOPRA helpful: 9 
[...] 

참고 출력 잘릴 ([...])

+0

그것은 일했습니다! 감사합니다 :) – Abhishek

+0

다른 페이지에있는 모든 리뷰를 얻을 필요가 있습니다. 페이지 번호 2 (매개 변수 '페이지')의 리뷰에 액세스하기 위해 referer 문자열을 수정하려고 시도했지만 첫 페이지에 리뷰가 계속 표시됩니다. 어떤 제안? – Abhishek

+0

시작 매개 변수를 추가하고 15의 배수로 값을 설정하십시오. 따라서 두 번째 페이지의 리뷰는 다음과 같습니다. https://www.flipkart.com/api/3/product/reviews?productId=MOBEFM5HAFRNSJJA&count=15&ratings=ALL&reviewerType= ALL & sortOrder = MOST_HELPFUL & start = 15 –

1

JSoup는 JavaScript를 실행하지 않고 HTML을 구문 분석 할 수 있지만 찾고있는 콘텐츠는 Jsoup이 인식하지 못하는 JavaScript로 페이지에 추가됩니다.

당신이 찾고있는 것을 얻으려면 셀레늄 같은 것이 필요합니다. 그러나 분석하려는 특정 사이트의 경우, 네트워크 활동에 대한 빠른 분석을 통해 찾고있는 모든 내용을 백엔드에서 가져옵니다. API 호출을 사용하고 Jsoup를 사용하지 않고도 훨씬 더 쉽게 액세스 할 수 있도록합니다. 작은 오이로

+0

Flipkart.com 페치하는 API를 가지고 제품을 백엔드에서 가져 왔지만 제품의 리뷰를 가져올 방법이 없습니다. 셀렌을 사용하지 않고 리뷰를 가져 오는 데 사용할 수있는 다른 대안은 무엇입니까? – Abhishek

+0

크롬 devtool로 네트워크 분석을 수행하십시오! – gherkin

+1

요청을 찾을 수 없지만 지금은 할 수 있습니다. 도움을 주셔서 감사합니다 :) – Abhishek