Javascript가 모든 웹 페이지의 소스를 읽을 수 있습니까?
화면 스크래핑 작업 중이며 특정 페이지의 소스 코드를 검색하고 싶습니다.
자바 스크립트로 어떻게 이것을 달성 할 수 있습니까? 제발 도와주세요.
시작하는 간단한 방법, jQuery 사용해보기
$("#links").load("/Main_Page #jq-p-Getting-Started li");
jQuery 문서 에서 더보기
훨씬 더 구조화 된 방식으로 화면 스크래핑을 수행하는 또 다른 방법은 YQL 또는 Yahoo Query Language를 사용하는 것입니다. JSON 또는 xml로 구조화 된 스크랩 된 데이터를 반환합니다.
예를 들어
stackoverflow.com을 긁어 보자
select * from html where url="http://stackoverflow.com"
다음과 같은 JSON 배열을 제공합니다 (이 옵션을 선택했습니다).
"results": {
"body": {
"noscript": [
{
"div": {
"id": "noscript-padding"
}
},
{
"div": {
"id": "noscript-warning",
"p": "Stack Overflow works best with JavaScript enabled"
}
}
],
"div": [
{
"id": "notify-container"
},
{
"div": [
{
"id": "header",
"div": [
{
"id": "hlogo",
"a": {
"href": "/",
"img": {
"alt": "logo homepage",
"height": "70",
"src": "http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png",
"width": "250"
}
……..
이것의 아름다움은 당신이 할 수 있다는 것입니다 계획과 궁극적으로 당신에게 구조화 긁어 데이터를 얻을 수있는 조항을 데이터 만 무엇을 필요 (궁극적으로 와이어를 통해 훨씬 적은 대역폭)
예를
select * from html where url="http://stackoverflow.com" and
xpath='//div/h3/a'
너를 얻을 것이다
"results": {
"a": [
{
"href": "/questions/414690/iphone-simulator-port-for-windows-closed",
"title": "Duplicate: Is any Windows simulator available to test iPhone application? as a hobbyist who cannot afford a mac, i set up a toolchain kit locally on cygwin to compile objecti … ",
"content": "iphone\n simulator port for windows"
},
{
"href": "/questions/680867/how-to-redirect-the-web-page-in-flex-application",
"title": "I have a button control ....i need another web page to be redirected while clicking that button .... how to do that ? Thanks ",
"content": "How\n to redirect the web page in flex application ?"
},
…..
이제 질문 만 얻으려면
select title from html where url="http://stackoverflow.com" and
xpath='//div/h3/a'
프로젝션 의 제목 에 유의하십시오.
"results": {
"a": [
{
"title": "I don't want the function to be entered simultaneously by multiple threads, neither do I want it to be entered again when it has not returned yet. Is there any approach to achieve … "
},
{
"title": "I'm certain I'm doing something really obviously stupid, but I've been trying to figure it out for a few hours now and nothing is jumping out at me. I'm using a ModelForm so I can … "
},
{
"title": "when i am going through my project in IE only its showing errors A runtime error has occurred Do you wish to debug? Line 768 Error:Expected')' Is this is regarding any script er … "
},
{
"title": "I have a java batch file consisting of 4 execution steps written for analyzing any Java application. In one of the steps, I'm adding few libs in classpath that are needed for my co … "
},
{
……
쿼리를 작성하면 URL이 생성됩니다.
우리의 경우.
그래서 궁극적으로 이런 일을하게됩니다.
var titleList = $.getJSON(theAboveUrl);
그것을 가지고 놀아 라.
아름답 지 않습니까?
도메인의 프록시를 통해 원하는 페이지를 가져 오는 한 Javascript를 사용할 수 있습니다.
<html>
<head>
<script src="/js/jquery-1.3.2.js"></script>
</head>
<body>
<script>
$.get("www.mydomain.com/?url=www.google.com", function(response) {
alert(response)
});
</script>
</body>
XmlHttp(AJAX)를 사용 하여 필요한 URL을 입력하면 URL의 HTML 응답을 responseText속성 에서 사용할 수 있습니다 . 동일한 도메인이 아닌 경우 사용자는 "이 페이지에서 다른 도메인에 액세스하려고합니다. 허용 하시겠습니까?"와 같은 내용의 브라우저 경고를 받게됩니다.
보안 조치로 Javascript는 다른 도메인의 파일을 읽을 수 없습니다. 이상한 해결 방법이있을 수 있지만이 작업에 대해 다른 언어를 고려할 것입니다.
jquery 사용
<html>
<head>
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js" ></script>
</head>
<body>
<script>
$.get("www.google.com", function(response) { alert(response) });
</script>
</body>
자바 스크립트를 꼭 사용해야하는 경우 ajax 요청으로 페이지 소스를로드 할 수 있습니다.
자바 스크립트를 사용하면 요청 페이지와 동일한 도메인에있는 페이지 만 검색 할 수 있습니다.
I used ImportIO. They let you request the HTML from any website if you set up an account with them (which is free). They let you make up to 50k requests per year. I didn't take them time to find an alternative, but I'm sure there are some.
In your Javascript, you'll basically just make a GET request like this:
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
jsontext = request.responseText;
alert(jsontext);
}
request.open("GET", "https://extraction.import.io/query/extractor/THE_PUBLIC_LINK_THEY_GIVE_YOU?_apikey=YOUR_KEY&url=YOUR_URL", true);
request.send();
Sidenote: I found this question while researching what I felt like was the same question, so others might find my solution helpful.
UPDATE: I created a new one which they just allowed me to use for less than 48 hours before they said I had to pay for the service. It seems that they shut down your project pretty quick now if you aren't paying. I made my own similar service with NodeJS and a library called NightmareJS. You can see their tutorial here and create your own web scraping tool. It's relatively easy. I haven't tried to set it up as an API that I could make requests to or anything.
You can generate a XmlHttpRequest and request the page,and then use getResponseText() to get the content.
You can use the FileReader API to get a file, and when selecting a file, put the url of your web page into the selection box. Use this code:
function readFile() {
var f = document.getElementById("yourfileinput").files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
alert(r.result);
}
r.readAsText(f);
} else {
alert("file could not be found")
}
}
}
You can bypass the same-origin-policy by either creating a browser extension or even saving the file as .hta in Windows (HTML Application).
Despite many comments to the contrary I believe that it is possible to overcome the same origin requirement with simple JavaScript.
I am not claiming that the following is original because I believe I saw something similar elsewhere a while ago.
I have only tested this with Safari on a Mac.
The following demonstration fetches the page in the base tag and and moves its innerHTML to a new window. My script adds html tags but with most modern browsers this could be avoided by using outerHTML.
<html>
<head>
<base href='http://apod.nasa.gov/apod/'>
<title>test</title>
<style>
body { margin: 0 }
textarea { outline: none; padding: 2em; width: 100%; height: 100% }
</style>
</head>
<body onload="w=window.open('#'); x=document.getElementById('t'); a='<html>\n'; b='\n</html>'; setTimeout('x.innerHTML=a+w.document.documentElement.innerHTML+b; w.close()',2000)">
<textarea id=t></textarea>
</body>
</html>
<script>
$.getJSON('http://www.whateverorigin.org/get?url=' + encodeURIComponent('hhttps://example.com/') + '&callback=?', function (data) {
alert(data.contents);
});
</script>
Include jQuery and use this code to get HTML of other website. Replace example.com with your website.
This method involves an external server fetching the sites HTML & sending it to you. :)
jquery is not the way of doing things. Do in purre javascript
var r = new XMLHttpRequest();
r.open('GET', 'yahoo.comm', false);
r.send(null);
if (r.status == 200) { alert(r.responseText); }
참고URL : https://stackoverflow.com/questions/680562/can-javascript-read-the-source-of-any-web-page
'IT TIP' 카테고리의 다른 글
| 'ABC'.replace ('B ','$` ')가 AAC를 제공하는 이유 (0) | 2020.11.01 |
|---|---|
| SET READ_COMMITTED_SNAPSHOT ON은 얼마나 걸리나요? (0) | 2020.10.31 |
| Django에서 새로운 사용자 지정 권한 추가 (0) | 2020.10.31 |
| npm의 일반 종속성에 대한 bundledDependencies의 장점 (0) | 2020.10.31 |
| 패딩에만 배경색을 추가 할 수 있습니까? (0) | 2020.10.31 |