[英]How do I output, in C++, all links from a saved .html file that are in the <a href> tags?
目前正在編寫一個程序,給定 URL,將在 .txt 文件中保存頁面 HTML 的副本,然后嘗試解析該 .txt 文件以獲取標簽中的超鏈接。 例子:
<a href="http://www.example.com">Visit example.com!</a>
現在,除了解析器之外的所有東西都可以工作。 我把output html文件的內容轉成a.txt。 然后我將它轉換成一個字符串,然后嘗試使用正則表達式解析該字符串,並將所有超鏈接存儲在一個向量中。 我認為打印出該向量的內容。 我的代碼解析部分的代碼如下:
vector<string> extract_hyperlinks(string html_file_name )
{
static const regex hl_regex( "<a href=\"(.*?)\">", regex_constants::icase ) ;
const string text = file_to_string(html_file_name) ;
sregex_token_iterator begin( text.begin(), text.end(), hl_regex, 1 );
sregex_token_iterator end ;
return vector<string>( begin, end ) ;
}
解析器沒有將任何內容放入向量中,即使字符串是用轉換為字符串的 .txt 文件填充的,該文件顯然包含諸如<a href="http://www.example.com">Visit example.com!</a>
之類的值<a href="http://www.example.com">Visit example.com!</a>
。
我做錯了什么,我該如何解決?
嘗試這個。
vector<string> extract_hyperlinks(string html_file_name )
{
static const regex hl_regex( "<a href=\"(.*?)\">", regex_constants::icase );
const string text = file_to_string(html_file_name) ;
std::vector<std::string> ret_vec;
std::copy( std::sregex_token_iterator(text.begin(), text.end(), hl_regex, 1),
std::sregex_token_iterator(),
std::back_inserter(ret_vec));
return ret_vec;
}
在這種情況下,正則表達式要么簡單到不充分,要么復雜到難以理解
根據 Martin York 的建議,您確實需要一個 HTML 解析庫。
我建議在https://github.com/google/gumbo-parser使用 goolge 的 gumbo-parser。 它是一個經過良好測試的純 C99 庫,有一些 C++ 個示例文件。 find_links.cc 示例文件做我認為你想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.