我一直在嘗試制作一個網路爬蟲工具來使用 bing 搜索引擎獲取所有 pastebin url。
我設法通過使用網路瀏覽器并讓 javascript 運行然后抓取所有源代碼來做到這一點。
string attempt = ""
^ 我有兩個問題。第一個問題是,如果我不寫該行MessageBox.Show(this.attempt),變數將由于某種原因為空。另一個問題是現在我只得到 9 個鏈接,它沒有像它應該的那樣下載其他頁面。我想這都是因為這MessageBox.Show(this.attempt)件事。
我知道我的代碼不是最好的,可能有很多更好的方法,但我想獲得幫助以了解這里發生了什么。
非常感謝
這是我的代碼:
private void Scan(Label pages)
{
string regex = @"https:\/\/pastebin.com\/[a-zA-Z0-9] ";
for (int i = 1; i <= Config.Amount_Of_Pages; i )
{
Parse(i);
MatchCollection matches = Regex.Matches(this.attempt, regex);
MessageBox.Show(this.attempt);
foreach (Match match in matches)
{
Config.List_Of_Urls.Add(match.Value.ToString());
Config.List_Of_Urls = Config.List_Of_Urls.Distinct().ToList();
}
Config.Amount_Of_Pages_Scanned ;
pages.Invoke(new MethodInvoker(delegate { pages.Text = Config.Amount_Of_Pages_Scanned.ToString(); }));
Files.Write_Urls(Config.List_Of_Urls);
}
MessageBox.Show("Done");
}
private void Parse(int i)
{
WebBrowser wb = new WebBrowser();
wb.DocumentCompleted = Wb_DocumentCompleted;
wb.ScriptErrorsSuppressed = true;
wb.Navigate("https://www.bing.com/search?q=site:pastebin.com email:password&first=" i);
}
private void Wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var wb = (WebBrowser)sender;
var html = wb.Document.GetElementsByTagName("HTML")[0].OuterHtml;
this.attempt = html.ToString();
/* ... */
}
uj5u.com熱心網友回復:
- 我更喜歡使用Selenium并為您推薦它。
- 如果你想獲得不同的 url,你應該使用HashSet而不是 List。
- 您應該將可選部分添加
(www\.)?到正則運算式。 - 為了處理重試策略,我更喜歡使用Polly
結果代碼為:
RetryPolicy retryPolicy = Policy.Handle<Exception>()
.WaitAndRetry(new[]
{
TimeSpan.FromSeconds(5),
TimeSpan.FromSeconds(10),
TimeSpan.FromSeconds(30)
});
string regex = @"https:\/\/(www\.)?pastebin.com\/[a-zA-Z0-9] ";
HashSet<string> sites = new HashSet<string>();
retryPolicy.Execute(() =>
{
using (IWebDriver driver = new ChromeDriver())
{
driver.Navigate().GoToUrl("https://www.bing.com/search?q=site:pastebin.com email:password&first=1");
// We have to wait until the page will download and rendered in the browser.
Thread.Sleep(1000);
foreach (Match match in Regex.Matches(driver.PageSource, regex))
{
sites.Add(match.Value);
}
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/483228.html
