2016-11-24 37 views
0

下面的代碼在我電腦上的java文件上運行,給出了「/ pws/client/pdf/offers-in-store-10-11-16」的正確結果.PDF「JSOUP html parse在android設備上給出不同的結果vs windows機器

   String pdfLink= null; 
        try { 


      Document doc = Jsoup.connect("http://www.dunnesstores.com/offer20/food-wine/fcp-category/home").get(); 
      Element links = doc.select("a[title=\"Download offers in store\"]").first(); 
      System.out.println(links.attr("href")); 


     } catch (IOException e) { 
      //e.printStackTrace(); 
     } 

然而,當我運行一個應用程序它是由按下按鈕激活的Android設備上的代碼,我得到一個空指針異常‘pdfLink = links.attr(’HREF」) ;」所以它沒有找到鏈接「/pws/client/pdf/offers-in-store-10-11-16.pdf」出於任何原因。在我的Android應用程序中,代碼位於按鈕的onclick監聽器上,通過代碼,它激活上點擊並運行的代碼行權,但無論出於何種原因JSOUP沒有找到link.Below是Android代碼

  public class MainActivity extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Button btnFetchData = (Button) findViewById(R.id.buttonTest); 
    btnFetchData.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      new FetchWebsiteData().execute(); 


     } 
    }); 

} 
private class FetchWebsiteData extends AsyncTask<Void, Void, Void> { 

    private String pdfLink = "didnt work"; 


    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 


    } 

    @Override 
    protected Void doInBackground(Void... params) { 
     try { 

      Document doc = Jsoup.connect("http://www.dunnesstores.com/offer20/food-wine/fcp-category/home").get(); 
      //Elements links = doc.select("a[title=\"Download offers in store\"]"); 
      Element links = doc.select("a[title=\"Download offers in store\"]").first(); 
      pdfLink=links.attr("href"); 


     } catch (IOException e) { 
      //e.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     TextView txttitle = (TextView) findViewById(R.id.resultTextView); 
     txttitle.setText(pdfLink); 

    } 

} 

    } 

回答

1

手機瀏覽器的用戶代理從桌面上的區別瀏覽器;因此,HTML響應不同。爲了獲得相同的結果,您必須設置桌面用戶代理。改變這一行:

Document doc = Jsoup.connect("http://www.dunnesstores.com/offer20/food-wine/fcp-category/home").get(); 

到:

Document doc = Jsoup.connect("http://www.dunnesstores.com/offer20/food-wine/fcp-category/home").userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").get(); 
相關問題