2011-02-17 65 views
0

I have an HTML file with very bad formatted code that I get from a website, I want to extract some very small pieces of information.搜索HTML线和删除线不与</form></td>​​<a

I am only interested in lines that start like this:

</form></td><td><a href="http://www.mysite.com/users/user897" class="username"> <b>user897</b></a></td></tr><tr><td>HouseA</td><td>2</td><td class="entriesTableRow-gamename">HouseA Type12 <span class="entriesTableRow-moredetails"></span></td><td>1 of 2</td><td>user123</td><td>10</td><td> 

and I want to extract 3 fields:

A:HouseA 
    B:HouseA Type12 
    C:user123 
    D:10 

I know I've seen people recommend HTML Agility Pack and lib2xml but I really don't think I need all that. My app is in C/C++.

I am already using getline to start reading lines, I am just not sure what's the best way to proceed. Thanks!

std::ifstream data("Home.html"); 
    std::string line; 
    while(std::getline(data,line)) 
    { 
     linenum++; 
     std::stringstream lineStream(line); 
     std::string  user; 
     if (strncmp(line.c_str(), "</form></td><td>",strlen("</form></td><td>")) == 0) 
     { 

      printf("found a wanted line in line:%d\n", linenum); 
     } 

    } 
+0

你有没有尝试用正则表达式解析你的HTML? :-p – 2011-02-17 22:48:43

+0

你有什么库可以使用C++ stdlib吗?你的目标是什么平台? – Macke 2011-02-17 22:51:14

回答

2

In the general case, an XML/HTML parser is likely the best way here, as it will be robust against differing input. (Whatever you do, don't use regexps开始!)

更新

但是,如果你靶向特定的输入,因为它似乎你做的,你可以使用sscanf(如你所建议的)或cin.read()或regexp手动扫描。

只要注意,这段代码可以在任何时候中断HTML的更改(即使只是使用空格)。

因此,我/我们的建议是使用适当的工具来完成这项工作。 XML/HTML不是原始文本,不应该这样对待。

如何编写一个python脚本呢? :)