我有Javascript puppeteer
代码,并且PuppeteerSharp for C#
. 我知道这个图书馆很相似,而且我知道他们的网站。
但是我的问题是我几乎无法管理这个库,每个库都有很多方法,而且很难找到需要的方法,即使我有用 JS 编写的工作示例。
请帮我将 JS 代码重写为 C#,这样它会做类似的事情。或者至少是函数名称,例如 JS (puppeteer) 方法 = C# (puppeteerSharp) 方法。
(async function main() {
try {
const browser = await puppeteer.launch();
const [page] = await browser.pages();
page.setDefaultTimeout(0);
await page.goto('www.example.com');
await page.waitForSelector('#search-content button.btn-icon');
let count = 0;
while (await page.$('#search-content button.btn-icon') !== null && count != 1) {
const articlesForNow = (await page.$$('#search-content article')).length;
console.log(`Articles for now: ${articlesForNow}. Getting more...`);
count += 1;
await Promise.all([
page.evaluate(
() => {
document.querySelector('#search-content button.btn-icon').click();
}
),
page.waitForFunction(
old => document.querySelectorAll('#search-content article').length > old, {},
articlesForNow
),
]);
}
const articlesAll = (await page.$$('#search-content article')).length;
console.log(`All articles: ${articlesAll}.`);
fs.writeFileSync('full.html', await page.content());
fs.writeFileSync('articles.html', await page.evaluate(
() => document.querySelector('#search-content div.b-filter__inner').outerHTML
));
fs.appendFileSync('articles.txt', await page.evaluate(
(fr) => {
let items = document.querySelectorAll(".product__body");
let appartmentsData = "";
for (let i = 0; i < items.length; i++) {
let itemLink = items[i].querySelector(".product__link").href;
let itemName = items[i].querySelector(".product__link strong").innerHTML;
let itemPrice = items[i].querySelector(".product__value").innerHTML;
return appartmentsData;
}, fr
));
// rest of the code
到目前为止我所拥有的:
using(var browser = await Puppeteer.LaunchAsync(new LaunchOptions())) {
var page = await browser.NewPageAsync();
await page.GoToAsync(LINK);
await page.WaitForSelectorAsync("#search-content button.btn-icon");
while (await page.QuerySelectorAsync("#search-content button.btn-icon") != null) {
var articlesForNow = await page.QuerySelectorAllAsync("#search-content article");
Console.WriteLine("Items proceed: " + articlesForNow.Length);
for (int i = 0; i < articlesForNow.Length; i++) {
string itemOuterHtml = await articlesForNow[i].EvaluateFunctionAsync < string > ("e => e.outerHTML");
}
await page.WaitForSelectorAsync("#search-content button.btn-icon").EvaluateFunctionAsync("e => e.click()");
}
}
但它是无限计数并且不会停止。在元素为 1275 之后,它会在 while 循环中引发有关我的方法的错误。
PuppeteerSharp.WaitTaskTimeoutException: waiting for selector '#search-content button.btn-icon' failed: timeout 30000ms exceeded