2011-08-14 2 views
1

URL의 페이지 제목을 얻기 위해 Groovy로 작성한 코드입니다. 그러나 일부 웹 사이트에서 "Moved Permanently"을 얻었습니다. 301 리디렉션 때문에 이것이라고 생각합니다. 나는이 문제를 방지하고 내가 대신 올바른 페이지 제목 http://www.nytimes.com/2011/08/14/arts/music/jay-z-and-kanye-wests-watch-the-throne.htmlHttpUrlConnection은 컨텐트의 제목을 가져오고 "Movated Permanently"을 받았습니다.

 

     def con = (HttpURLConnection) new URL(url).openConnection() 
     con.connect() 

     def inputStream = con.inputStream 

     HtmlCleaner cleaner = new HtmlCleaner() 
     CleanerProperties props = cleaner.getProperties() 

     TagNode node = cleaner.clean(inputStream) 
     TagNode titleNode = node.findElementByName("title", true); 

     def title = titleNode.getText().toString() 
     title = StringEscapeUtils.unescapeHtml(title).trim() 
     title = title.replace("\n", ""); 
     return title 
 

답변

1
나는

제가 문제가 사이트가 쿠키를 기대하는 것입니다 생각 ... 나는 나 자신을 리디렉션 관리하는 경우이 작업을 얻을 수

이 그것을 리다이렉트 체인의 절반을 전송하고, 리다이렉트 체인을 얻지 못하면 로그인 페이지로 이동합니다.

이 코드는 분명히 몇 가지 정리 필요 (아마도이 ​​할 수있는 더 좋은 방법이있다)하지만, 내가 제목을 추출 할 수있는 방법을 보여줍니다

@Grab('net.sourceforge.htmlcleaner:htmlcleaner:2.2') 
@Grab('commons-lang:commons-lang:2.6') 
import org.apache.commons.lang.StringEscapeUtils 
import org.htmlcleaner.* 

String location = 'http://www.nytimes.com/2011/08/14/arts/music/jay-z-and-kanye-wests-watch-the-throne.html' 
String cookie = null 
String pageContent = '' 

while(location) { 
    new URL(location).openConnection().with { con -> 
    // We'll do redirects ourselves 
    con.instanceFollowRedirects = false 

    // If we got a cookie last time round, then add it to our request 
    if(cookie) con.setRequestProperty('Cookie', cookie) 
    con.connect() 

    // Get the response code, and the location to jump to (in case of a redirect) 
    int responseCode = con.responseCode 
    location = con.getHeaderField("Location") 

    // Try and get a cookie the site will set, we will pass this next time round 
    cookie = con.getHeaderField("Set-Cookie") 

    // Read the HTML and close the inputstream 
    pageContent = con.inputStream.withReader { it.text } 
    } 
} 

// Then, clean paceContent and get the title 
HtmlCleaner cleaner = new HtmlCleaner() 
CleanerProperties props = cleaner.getProperties() 

TagNode node = cleaner.clean(pageContent) 
TagNode titleNode = node.findElementByName("title", true); 

def title = titleNode.text.toString() 
title = StringEscapeUtils.unescapeHtml(title).trim() 
title = title.replace("\n", "") 

println title 

가 도움이 희망을!

0

의 "영구적으로 이동"있어이 웹 사이트를 HttpURLConnection의 오른쪽 URL에 따라하자 예를 들어 올바른 페이지 제목

을 얻는 방법 HttpUrlConnection에서 setInstanceFollowRedirects (true)를 호출해야합니다. 즉, 첫 번째 줄 이후 (사실) con.setInstanceFollowRedirects를 삽입

+0

나는 그것을 시도했지만 여전히 작동하지 않았다. 그리고 setInstainceFollowRedirects (true)가 기본값이라고 생각합니다. 하지만 고맙습니다. 답장을 보내 주시면 감사하겠습니다. – toy

+0

그래, 내가 게시하기 전에 자신을 시도해야합니다. 나는 당신의 증상을 재현했지만 아직 그 이유를 알지 못합니다. 나는 HttpUrlConnection 대신에 HttpBuilder를 시도했고, additonal 설정없이 리다이렉트를 따른다. 그러나 결과물을 HtmlCleaner로 전달할 수 없었습니다. – mmigdol

+0

그것은 영향을 미치지 않는 페이 월이 아닙니까? –

관련 문제