Javascript for google image ripping broke with update - javascript

I grabbed a few small scripts and threw them together to take google's new image layout and turn back into the old one, then take the images and replace them with the full size versions. Worked great until about last week. Not sure what changed on the server side.
(function() {
// Get list of all anchor tags that have an href attribute containing the start and stop key strings.
var fullImgUrls = selectNodes(document, document.body, "//a[contains(#href,'/imgres?imgurl\x3d')][contains(#href,'\x26imgrefurl=')]");
//clear existing markup
var imgContent = document.getElementById('ImgContent');
imgContent.innerHTML = "";
for(var x=1; x<=fullImgUrls.length; x++) {
//reverse X to show images in correct order using .insertBefore imgContent.nextSibling
var reversedX = (fullImgUrls.length) - x;
// get url using regexp
var fullUrl = fullImgUrls[reversedX].href.match( /\/imgres\?imgurl\=(.*?)\&imgrefurl\=(.*?)\&usg/ );
// if url was fetched, create img with fullUrl src
if(fullUrl) {
newLink = document.createElement('a');
imgContent.parentNode.insertBefore(newLink , imgContent.nextSibling);
newLink.href = unescape(fullUrl[2]);
newElement = document.createElement('img');
newLink.appendChild(newElement);
newElement.src = decodeURI(fullUrl[1]);
newElement.border = 0;
newElement.title = fullUrl[2];
}
}
function selectNodes(document, context, xpath) {
var nodes = document.evaluate(xpath, context, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
var result = [];
for (var x=0; x<nodes.snapshotLength; x++) {
result.push(nodes.snapshotItem(x));
}
return result;
}
})();

Google changed the 'ImgContent' id for the image table holder to something slightly more obscure. A quick change had everything working again. I made a simple problem complicated by looking past the easy stuff. Thanks to darvids0n for the enabling, he ultimately pointed out what I was missing.

the script is not going to work as said by bobby .
try this grease monkey script from user script repository.
rip Google image search :- http://userscripts.org/scripts/show/111342

Related

Retrieve the hyperlink on a specific text string within Google Doc using Apps Script

I'm trying to use Google Apps Script to get the hyperlink from a specific string found in this Google Doc.
The string is ||stock||
The hyperlink is https://www.cnbc.com/quotes/?symbol=aapl&qsearchterm=aapl
Any help is greatly appreciated.
The code I'm currently using
function docReport() {
var doc = DocumentApp.openByUrl('https://docs.google.com/document/d/1XNiqgJ_hM2SWjoR-OTsq1w-ZFKvTIERDIs_NOWJpckY/edit');
var body = doc.getBody();
Logger.log(body.getParagraphs().length);//get the number of paragraphs
//https://www.udemy.com/apps-script-course/learn/v4/t/lecture/10208226?start=0
for (var x=0;x<body.getParagraphs();X++) {
var el = body.getChild(x);
Logger.log(el.getText());
}
var bodyText = body.getText();
var words = bodyText.match(/\S+/g); // get word count for body - https://stackoverflow.com/questions/33338667/function-for-word-count-in-google-docs-apps-script
Logger.log(words.length); // retruns # of words
var paragraphAll = body.getParagraphs(); // gets all paragraph objects in a document
Logger.log(paragraphAll);
var paragraphText = paragraphAll[1].getText().match(/\S+/g);
Logger.log(paragraphText.length); // retruns # of words in a paragraph
}
You want to retrieve hyperlink of the text of ||stock||.
If my understanding is correct, for example, how about this sample script? In your situation, the text value which has a link has already been known. The sample script uses this situation.
By the way, from your question, I'm not sure whether there are several values of ||stock|| in the document. So this sample script supposes that there are several values of ||stock|| in the document.
I think that there are several answers for your situation. So please think of this as one of them.
Sample script:
var searchValue = "\\|\\|stock\\|\\|"; // Search value
var body = DocumentApp.openByUrl('https://docs.google.com/document/d/1XNiqgJ_hM2SWjoR-OTsq1w-ZFKvTIERDIs_NOWJpckY/edit').getBody();
var searchedText = body.findText(searchValue);
var urls = [];
while (searchedText) {
var url = searchedText.getElement().asText().getLinkUrl(searchedText.getStartOffset());
urls.push(url);
searchedText = body.findText(searchValue, searchedText);
}
Logger.log(urls) // Results
Note:
If there is only one search value in the document, you can also use the following script.
var searchValue = "\\|\\|stock\\|\\|";
var body = DocumentApp.openByUrl('https://docs.google.com/document/d/1XNiqgJ_hM2SWjoR-OTsq1w-ZFKvTIERDIs_NOWJpckY/edit').getBody();
var searchedText = body.findText(searchValue);
var url = searchedText.getElement().asText().getLinkUrl(searchedText.getStartOffset());
Logger.log(url)
References:
findText()
getLinkUrl()
If I misunderstand your question, please tell me. I would like to modify it.

Extracting img urls from webpage using Google Apps Script

This is an Apps Script that goes through a webpage and collects img urls that are inside some div of a special class.
function getIMGs(url){
var url = 'url'
var result = UrlFetchApp.fetch(url);
if (result.getResponseCode() == 200) {
var doc = Xml.parse(result, true);
var bodyHtml = doc.html.body.toXmlString();
var doc = XmlService.parse(bodyHtml);
var html = doc.getRootElement();
var thumbs = getElementsByClassName(html, 'thumb');
var sheet = SpreadsheetApp.getActiveSheet();
for (i in Thumbs) {
var output = '';
var linksInMenu = getElementsByTagName(thumbs[i], 'img');
for(i in linksInMenu) {
output += XmlService.getRawFormat().format(linksInMenu[i]);
}
var linkRegExp = /data-src="(.*?)"/;
var dataSrc = linkRegExp.exec(output);
sheet.appendRow([dataSrc[1]]);
}
}
So first the code gets the html, and uses an auxiliary function to get certain elements, which look like this:
<div class="thumb"><div class="loader"><span class="icon-uniE611"></span></div><img src="//xxx" data-src="https://xxx/8491a83b1cacc2401907997b5b93e433c03c91f.JPG" data-target="#image-slider" data-slide-to="0"></div>
Then the code gets the img elements, and finally extracts the data-src address via RegExp.
While this kinda works, I have a problem:
1) After 9 loops it crashes, on the appendRow line, as the last 4 Thumbs elements don't have data-src, hence what i'm trying to write into the spreadsheet is null.
Any solution for this? I have fixed it for the moment by just doing 9 iterations only of the For loop, but this is far from optimal, as it's not automated and required me to go through the page to count the elements with data-src.
Also, any suggestion of a more elegant solution will be appreciated! I will be really grateful for any helping hand!
Cheers

Extract PresentationNotes from keynote

I'm having a hard time extracting presentationNotes from a keynote presentation using JXA (Javascript for osx) I don't want to use applescript. There is way more to this script than extracting notes.
It seems rather simple. However when I get the presentationNotes its in an RichText object that doesn't seem to have anyway to get normal text.
So I figured I'd open up textEditor and write them out to it.
Well I can't figure out how to do that.
var app = Application('Keynote')
document = app.documents[0]
slide_name = document.name()
i = 1 // loop through folder contents
folder_name = 'chapter'+i
//create a folder
var textEdit = Application('textEdit')
textEdit.activate()
var doc = textEdit.make({new:'document'})
doc.text = "fsdfsdfs"
var c = 0;
for(slide in document.slides){
var s = document.slides[slide]
var note = s.presentationNotes // returns object specifier
//textEdit.documents[0].push(note)
// I've tried lots of things here.
}
Any ideas or help would be appreciated. I've seen some applescript examples, however I couldn't get them to translate. Apparently applescript as text doesn't relate to toString()
You were almost there. You should not push the text, but push a paragraph object of the text.
Here is a complete example (text only).
It uses the currently open Keynote and TextEdit documents.
var Keynote = Application("Keynote");
var presentation = Keynote.documents[0];
var TextEdit = Application("TextEdit");
var document = TextEdit.documents[0];
document.paragraphs.push( TextEdit.Paragraph({color:"red", size:18}, "presentation: "+ presentation.name()+"\n" ))
for (var i=0; i<presentation.slides.length; i++) {
slide = presentation.slides[i];
slideTitle = slide.defaultTitleItem().objectText();
notes = slide.presenterNotes(); // text only
document.paragraphs.push( TextEdit.Paragraph({color:"blue", size:14}, "\n"+ (i+1) +": "+ slideTitle + "\n") )
document.paragraphs.push( TextEdit.Paragraph({}, notes +"\n") )
}

How to change the URL of an image tag on every click on the image using JavaScript?

I have an element displaying an image on an HTML page. This element's source is one of many different images in a JavaScript array.
I already have a script for looping through the images, creating a slideshow effect, but now I want to manually flick through the images with buttons.
This is my code so far, but I get no response when clicking the button.
function nextup()
{
imgs = [];
imgs[0] = "/snakelane/assets/images/thumb/_1.jpg"; imgs[10] = "/snakelane/assets/images/thumb/_19.jpg";
imgs[1] = "/snakelane/assets/images/thumb/_2.jpg"; imgs[11] = "/snakelane/assets/images/thumb/_20.jpg";
imgs[2] = "/snakelane/assets/images/thumb/_3.jpg"; imgs[12] = "/snakelane/assets/images/thumb/_21.jpg";
imgs[3] = "/snakelane/assets/images/thumb/_4.jpg"; imgs[13] = "/snakelane/assets/images/thumb/_22.jpg";
imgs[4] = "/snakelane/assets/images/thumb/_5.jpg"; imgs[14] = "/snakelane/assets/images/thumb/_23.jpg";
imgs[5] = "/snakelane/assets/images/thumb/_6.jpg"; imgs[15] = "/snakelane/assets/images/thumb/_24.jpg";
imgs[6] = "/snakelane/assets/images/thumb/_7.jpg"; imgs[16] = "/snakelane/assets/images/thumb/_25.jpg";
imgs[7] = "/snakelane/assets/images/thumb/_8.jpg"; imgs[17] = "/snakelane/assets/images/thumb/_26.jpg";
imgs[8] = "/snakelane/assets/images/thumb/_9.jpg"; imgs[18] = "/snakelane/assets/images/thumb/_27.jpg";
imgs[9] = "/snakelane/assets/images/thumb/_32.jpg"; imgs[19] = "/snakelane/assets/images/thumb/_28.jpg";
var pic = document.getElementById("picbox");
for(i =0; i < imgs.length; i++) {
var current = indexOf(pic.src);
var next = Math.round(current + 1);
pic.src = imgs[next];
}
}
Can anyone tell me what's wrong with my code or suggest a better way?
Multiple problems in the approach you had used. Have a look at the modified function below. Let me know if you need explanation with anything.
The following code will use an array containing image URLs and later assign in a sequential manner to an img tag on click. Enjoy!
Here you can try to see the output.
function nextup(){
//Initialized img array with 10 images, you can do it any way you want to.
var imgs = [];
for(i=0;i<10;i++){
imgs[i] = "http://lorempixel.com/output/cats-q-c-100-100-"+(i+1)+".jpg";
}
//Fetch the pic DOM element by ID
var pic = document.getElementById("picbox");
//Know what is position of currently assigned image in array.
var current = imgs.indexOf(pic.src);
var next = 0;
//Handle case if no image is present, the initial case.
if(current!=-1){
next = (current + 1)%(imgs.length);
}
//Assign the next src
pic.src = imgs[next];
}
//Scoped outside to call the function first time on load.
nextup();
I found the following problems in your code:
You tried to use indexOf without specifying the array in which the search has to be performed. Imagine s school principal asking someone to go find if John is present in the classroom without specifying a specific classroom.
For iterating through array you used a next variable which could have been a good idea if you needed an endless loop. But here since we are limited to 10 or 20 images we need to make sure that if the currently selected image is the last one, we find that next goes to 21 (assuming a total of 20 images.) and this would try to access a variable out of bounds.
Hence I've used the mod operator %.
For reference in JavaScript, 5%10 would return 5 , 15%10 would return 5 and so on. Read more about the mod operator HERE.

Random element from an array of images and their respective links on page refresh

I've got an unordered list of images. I'd like for each of those images to have an href attribute (since I would like to use a lightbox-popup to display the correlating image when clicked), but for each image to be random when the page is refreshed.
In short, for each image coupled with its href to be random, but the order of the ul to stay the same. What would be a way of achieving this?
var img_array = []; //assuming your array is called this and full of porn pictures
//fisher-yates algorithm. Google it
(function(){
var tmp, current, top = img_array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = img_array[current];
img_array[current] = img_array[top];
img_array[top] = tmp;
}
})();
//target html element where the images are appended
var target = document.getElementById('someTargetDiv');
for(var i=0, len=img_array.length; i<len; i++){
var link = document.createElement('a'),
img = document.createElement('img');
link.setAttribute('href', img_array[i]);
img.setAttribute('src', img_array[i]);
link.appendChild(img);
target.appendChild(link);
}
This is not an optimized way of doing this kind of operation. I've made it slightly more verbose for your understanding.
The biggest mistake with this code is the constant creation of many different elements and appending them to the DOM one at a time. What should really be done is to build a string of generated html, and changing the innerHTML of a target div in one operation.
var html = [];
for(var i=0, len=img_array.length; i<len; i++){
html.push('<img src="'+ img_array[i] +'">');
}
target.innerHTML = html.join('');
Hopefully I get this right.
With jQuery you could do it like this jsfiddle:
$('ul').children('li').sort(function() {
return Math.round(Math.random()); // randomly get 0 or 1
}).appendTo('ul');
Doing it with PHP on server side would make more sense, but since you have no db resource or so, you'd have to make a static array of image:link pairs then shuffle it and generate a random list.
UPDATE
Maybe this comes closer to a solution:
jsfiddle
var contents = new Array(),
$list = $('li');
$list.each(function() { contents.push($(this).children()); });
contents.sort(function() {
return 0.5 - Math.random();
});
$list.each(function() {
$(this).append(contents.shift());
});

Categories

Resources