我想刮掉http://www.menorcarentals.com/en/villas的alle頁,但我有一些問題,因爲它每次給我的第一頁。 我的方法是查找頁面上的所有輸入和選擇,並將__EVENTTARGET的值設置爲我想要單擊的按鈕的值,這些按鈕之前都有效,但是此站點不會執行更改。刮ASP.NET頁面,模擬點擊
方法來獲取所有輸入字段
public static Dictionary<string, string> GetInputFields(CQ dom)
{
Dictionary<string, string> result = new Dictionary<string, string>();
foreach (var v in dom.Find("input"))
{
var value = v.Cq().Attr("value");
var key = v.Cq().Attr("name");
if (!string.IsNullOrWhiteSpace(value))
{
if (!result.ContainsKey(key))
{
result.Add(key, value);
}
else
{
result[key] = value;
}
}
}
// Get all selects
foreach (var s in dom.Select("select"))
{
var select = s.Cq();
var key = select.Attr("name");
foreach (var option in select.Children("option"))
{
var opt = option.Cq();
if(!string.IsNullOrWhiteSpace(opt.Attr("selected")))
{
if (!result.ContainsKey(key))
{
result.Add(key, opt.Val());
}
else
{
result[key] = opt.Val();
}
}
}
}
return result;
}
我的代碼雖然不同的網頁,在瀏覽器中的cookies(刪除關閉之前餅乾),比沿運行
string searchPageUrl = "http://www.menorcarentals.com/en/villas";
var html = DownloadHelper.Download(searchPageUrl);
while (true)
{
CQ dom = html;
// parse page and get info i need here
// Find the next page
var pagination = dom.Select("#ctl00_Content_dpVillas").Children();
bool foundCurrent = false;
string clickElementName = string.Empty;
foreach (var pagi in pagination)
{
if (pagi.Classes.Any(x=>x.ToLower() == "current"))
{
foundCurrent = true;
}
else if (foundCurrent)
{
var href = pagi.Cq().Attr("href");
clickElementName = RegexHelper.Match(@"doPostBack\(\'([^']+)", href);
break;
}
}
if (string.IsNullOrWhiteSpace(clickElementName))
{
break; // no more pages
}
var inputFields = ScraperHelper.GetInputFields(html);
// Simulate that we click the next button
if (!inputFields.ContainsKey("__EVENTTARGET"))
inputFields.Add("__EVENTTARGET", String.Empty);
inputFields["__EVENTTARGET"] = clickElementName;
html = DownloadHelper.Post(searchPageUrl, inputFields);
}
警告!你正在使用正則表達式來解析HTML,[這是一個壞主意](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 )。 – mason 2015-03-02 21:27:27
看起來他只是用正則表達式解析href。他在其他地方使用CsQuery。 – Amy 2015-03-02 22:15:28