Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get all images with xpath

Tags:

xpath

I'm trying to get all image from u list in HTML with Hpple and xpath but no benefit

my HTML node like these

<ul id="week_slider">
      <div id="week_program_img">
            <img id="Img1" src="imageurl">    
      </div>
</ul>

but some times (img) tags be inside (a) tags like this

<a href="url">
       <img id="Img1" src="imageurl"> 
</a>

and I can get only the images (which not in 'a' tags) when put this path in xpath

//ul[@id='week_slider']//div[@id='week_program_img']

also I can get images (which in 'a' tags) when put this path in xpath

//ul[@id='week_slider']//div[@id='week_program_img']/a

but I want to get all of images in same time both of in or without tags how can i do this in same xpath ? i try use (or) , (|) , (and) operators like this

//ul[@id='week_slider']//div[@id='week_program_img'] | //ul[@id='week_slider']//div[@id='week_program_img']/a 

but it's not working fine

my full code :

NSString *tutorialsXpathQueryStringimage1 = @"//ul[@id='week_slider']//div[@id='week_program_img']";

NSArray *newsNodesimage1 = [newsParser searchWithXPathQuery:tutorialsXpathQueryStringimage1];




NSMutableArray *image1 = [[NSMutableArray alloc] initWithCapacity:0];
for (TFHppleElement *element in newsNodesimage1) {



    Tutorial *tutorial = [[Tutorial alloc] init];
    [image1 addObject:tutorial];

    for (TFHppleElement *child in element.children) {
        if ([child.tagName isEqualToString:@"img"]) {

            tutorial.imageUrl = [child objectForKey:@"src"];
        }
    }


}
like image 256
aqeel Avatar asked Oct 22 '25 15:10

aqeel


2 Answers

Use:

//ul[@id='week_slider']//div[@id='week_program_img']//img

Or in case you want to select the parent of every such image, which seems to be the case based on the provided XPath expressions, use:

//ul[@id='week_slider']//div[@id='week_program_img']/descendant-or-self::*[img]
like image 179
Dimitre Novatchev Avatar answered Oct 26 '25 00:10

Dimitre Novatchev


Late to the party but here is another way:

//ul[@id='week_slider']//descendant::img

The nice thing is that descendant selects all descendants (children, grandchildren, etc.) of the current node. In this case, all images that exist in a div with id='week_slider.

You can also select images by index, i.e.

//descendant::img[1]
like image 32
benscabbia Avatar answered Oct 26 '25 00:10

benscabbia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!