Reputation: 25
I have a table that I screen scraped using the jQuery load function, the function returns a table with text and graphics. The website I scraped from uses relative paths for their images so when I return the code to my page the images are not showing up. I have been looking for a jQuery function to find the tag and either update it to add the scrapped sites url into the src attribute, but not having much luck.
The current tag looks like this:
<img style="border:thin solid black; margin-top:5-x;" src="/images/picture.jpg">
What I need to do is insert the http://www.somesite.com into the src atttribute, so it looks like this:
<img style="border:thin solid black; margin-top:5-x;" src="http://www.somesite.com/images/picture.jpg">
Can anyone point me to the proper feature I need to do this?
Thanks!
Upvotes: 0
Views: 290
Reputation: 20992
It's returned as a text string right (albeit with html tags). So you could just manipulate the text directly:
data = data.replace(/<img(.*?)src="/ig,'<img$1src="http://somesite.com')
EDIT: Sorry, just realized load puts the content directly in there. Unless there's a compelling reason to do so, don't use load. Instead, use $.get and then insert the text.
So instead of:
$("el").load(url);
Use:
$.get(url, function (data) {
data = data.replace(/<img(.*?)src="/ig,'<img$1src="http://somesite.com');
$("el").html(data);
}
);
Upvotes: 0
Reputation: 8400
$("table img").each(function(){
$(this).attr("src", "http://www.somesite.com" + $(this).attr("src"));
});
<script src="path_to_jquery.js"></script>
<script>
$(document).ready(function(){
$("#table").load("target_website table:nth-child(3)", function(){
// info: actually I'm not sure if this inside this function will be #table
// you look for each image in #table...
$(this).find("img").each(function(){
// ...and do things with src attribute of each image
$(this).attr("src", "http://www.somesite.com" + $(this).attr("src"));
});
});
});
</script>
<div id="table"></div>
Upvotes: 1