C语言解析html网页中的图片URL

实例:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <regex.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

static const char * HREF_PATTERN = "<img [^>]*src=\"\\s*\\([^ >\"]*\\)\\s*\"";                                 

int main(int argc, char** argv){
    int n ,len, count;
    regex_t re; 
    const size_t nmatch = 2;
    regmatch_t matchptr[nmatch];
    char *p = NULL;
    char str[1024*1024];

    memset(str, 0, sizeof(str));
    n = 0;
    count = 0;

    //operate file and read contents
    int fd = open(argv[1], O_RDONLY);
    if (fd < 0) {
        printf("file:%s open error\n", argv[1]);
        return -1; 
    }   
    
    while ((n = read(fd, str+count, 1024)) != 0) {
        if (n == -1) {
            printf("file read error\n");
            return -1; 
        }   
    
        count += n;

    }   
    close(fd);
    printf("\nfile read over! begin URL analyse now...\n");

    p = str;

    if (regcomp(&re, HREF_PATTERN, 0) != 0) {/* compile error */
        printf("compile regex error\n");
    }   

    while (regexec(&re, p, nmatch, matchptr, 0) != REG_NOMATCH) {
        len = (matchptr[1].rm_eo - matchptr[1].rm_so);
        p = p + matchptr[1].rm_so;
        char *tmp = (char *)calloc(len+1, 1); 
        strncpy(tmp, p, len);
        tmp[len] = '\0';
        p = p + len + (matchptr[0].rm_eo - matchptr[1].rm_eo);
        printf("%s\n", tmp);
    }   
    
    return 0;
}

运行结果:

gcc test.c -o test
./test www.zol.com.cn_webcenter_map.html 

file read over! begin URL analyse now...
https://dg-fd.zol-img.com.cn/t_s2000x2000/g5/M00/08/00/ChMkJ1YYZveITXKkAAADVZen7iIAADfxQO_-UMAAANt785.png
https://dg-fd.zol-img.com.cn/t_s2000x2000/g4/M00/06/07/Cg-4zFUCTDGIbtftAAAB8xYSy2YAAWoVALpfBUAAAIL673.png
https://dg-fd.zol-img.com.cn/t_s2000x2000/g4/M08/06/08/Cg-4zFUCVDuIXpdBAAABlOjlfjUAAWoXAP__gQAAAH8892.png
https://dg-fd.zol-img.com.cn/t_s2000x2000/g5/M00/08/0C/ChMkJ1ez0HiILQTIAAAPmt4wdOoAAUgUAN2Y3IAAA-y501.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

行走在软件开发路上的人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值