page.evaluate로 인수 전달
나는 PhantomJS page.evaluate ()를 사용하여 스크래핑을하고 있습니다. 내 문제는 내가 웹킷 페이지에 전달하는 코드가 샌드 박스 처리되어 있으므로 기본 팬텀 스크립트의 변수에 액세스 할 수 없다는 것입니다. 이것은 스크래핑 코드를 일반화하기 어렵게 만듭니다.
page.open(url, function() {
var foo = 42;
page.evaluate(function() {
// this code has no access to foo
console.log(foo);
});
}
페이지에 인수를 어떻게 밀어 넣을 수 있습니까?
나는 그 정확한 문제가 있었다. page.evaluate
문자열도 받아 들일 수 있기 때문에 약간의 속임수로 할 수 있습니다.
이를 수행하는 방법에는 여러 가지가 있지만 evaluate
웹킷 측에서 평가해야하는 함수에 전달할 추가 매개 변수를 허용하는 라는 래퍼를 사용 합니다. 다음과 같이 사용합니다.
page.open(url, function() {
var foo = 42;
evaluate(page, function(foo) {
// this code has now has access to foo
console.log(foo);
}, foo);
});
그리고 여기에 evaluate()
기능이 있습니다 :
/*
* This function wraps WebPage.evaluate, and offers the possibility to pass
* parameters into the webpage function. The PhantomJS issue is here:
*
* http://code.google.com/p/phantomjs/issues/detail?id=132
*
* This is from comment #43.
*/
function evaluate(page, func) {
var args = [].slice.call(arguments, 2);
var fn = "function() { return (" + func.toString() + ").apply(this, " + JSON.stringify(args) + ");}";
return page.evaluate(fn);
}
변경 사항이 적용되었으며 이제 다음과 같이 사용할 수 있습니다.
page.open(url, function() {
var foo = 42;
page.evaluate( function(foo) {
// this code has now has access to foo
console.log(foo);
}, foo);
}
푸시 세부 정보는 여기에 있습니다 : https://github.com/ariya/phantomjs/commit/81794f9096
PhantomJS 0.9.2 및 0.2.0에서 작동하는 솔루션이 있습니다.
page.evaluate(
function (aa, bb) { document.title = aa + "/" + bb;}, //the function
function (result) {}, // a callback when it's done
"aaa", //attr 1
"bbb"); //attr 2
page.evaluate에 대한 인수로 함수에 인수를 전달할 수 있습니다.
예:
page.evaluate(function(arg1, arg2){
console.log(arg1); //Will print "hi"
console.log(arg2); //Will print "there"
}, "hi", "there");
또 다른 가능성은 URL과 함께 변수를 전달하는 것입니다. 예를 들어 객체 x를 전달하려면
// turn your object "x" into a JSON string
var x_json = JSON.stringify(x);
// add to existing url
// you might want to check for existing "?" and add with "&"
url += '?' + encodeURIComponent(x_json);
page.open(url, function(status){
page.evaluate(function(){
// retrieve your var from document URL - if added with "&" this needs to change
var x_json = decodeURIComponent(window.location.search.substring(1));
// evil or not - eval is handy here
var x = eval('(' + x_json + ')');
)}
});
이것은 나를 위해 작동합니다.
page.evaluate("function() {document.body.innerHTML = '" + size + uid + "'}");
모든 것을 문자열로 넣는 것을 의미합니다. 어쨌든 나중에 그것은 문자열이됩니다. 라이브러리 소스를 확인하십시오.
인수를 함수에 바인딩 할 수 없습니까 ??
page.evaluate.bind(args)(callbackFn)
인수를 eva (function, arg1, arg2, ...)에 전달할 수 있지만 이것은 종종 약간 번거 롭습니다. 특히 여러 변수 또는 더 나쁜 함수를 전달할 때.
이 장애물을 피하려면 대신 injectJs (filename) 를 사용할 수 있습니다 .
page.open(url, function() {
if ( webpage.injectJs('my_extra_functionality.js') ) {
page.evaluate( function() {
// this code has access to foo and also myFunction();
console.log(foo);
console.log(myFunction());
});
}
else {
console.log("Failed to inject JS");
}
}
Where my_extra_functionality.js
is a local file in the same directory:
var foo = 42;
var myFunction = function(){
return "Hello world!";
}
ReferenceURL : https://stackoverflow.com/questions/9838119/pass-arguments-with-page-evaluate
'programing' 카테고리의 다른 글
소프트 키보드가 나타나면 EditText 필드가 포커스를 잃게됩니다. (0) | 2021.01.17 |
---|---|
양식의 버튼을 클릭하면 양식이 제출됩니다. (0) | 2021.01.17 |
smartgit "git-am is in progress"리베이스 (0) | 2021.01.17 |
데이터베이스가 QuerySet.dates ()에서 잘못된 값을 반환했습니다. (0) | 2021.01.17 |
Django 관리자의 필드에 클릭 가능한 링크를 추가하는 방법은 무엇입니까? (0) | 2021.01.17 |