我正在寻找:
(www.source.com/1 below)
(e.g. www.urllookingfor.com/1 to .../10)
上的所有URL并登录到控制台(e.g. www.source.com/2)
想象一下,在5个页面上有50个网址分红的列表,您需要单击next
按钮才能在页面上移动。
前两个步骤工作正常,但是我认为问题在于nextLink
在循环再次运行之前未更新。本质上发生的是,使用原始URL而不是“新” URL重复了第四步。上面的步骤在if循环内。
我尝试使用setTimeout
,async
... await
,因为我认为问题在于没有时间在下一个URL之前加载“新” URL功能已经完成,但是没有用。
如果我在if函数中添加console.log(URL)
,它将打印原始URL。但是,当我在if循环之外添加console.log
时,它会打印更新的URL,这使我认为'nextLink'直到if循环之后才更新。
我也尝试过反复地重复这些功能(本质上是重复if语句),但这似乎并没有在下一个函数运行之前更新'nextLink',这与上面的情况相反。
let nextLink = www.source.com/1
//this pulls source page and scrapes required URLs
const getDatafromPage = () => {
request(nextLink, (error, response, html) => {
if((!error) && (response.statusCode == 200))
{
let $ = cheerio.load(html);
$('.class1').each((i, el) => {
let link = $(el).find('.class2').attr('href');
console.log(`${link});
})
}
})
}
//this gets the next URL
const getNextLink = () => {
request(nextLink, (error, response, html) => {
if((!error) && (response.statusCode == 200))
{
let $ = cheerio.load(html);
nextLink = $('.class3').attr('href');
}
})
}
for (let i = 0; i <= 4; i++) {
getDatafromPage();
getNextLink();
}
console.log(nextLink)
预期结果(页面中的所有50个URL,并通过记录最后一个源URL结束)
www.urllookingfor.com/1
...
www.urllookingfor.com/50
www.source.com/5
实际结果(重复第一页,但最后记录下一页):
www.urllookingfor.com/1
...
www.urllookingfor.com/10
www.urllookingfor.com/1
...
www.urllookingfor.com/10
www.source.com/2
答案 0 :(得分:0)
在执行此操作时,它或多或少是这样的:
const doPage = async ($) => {
// do stuff here
}
;(async function(){
let response = await request(url)
let $ = cheerio.load(response)
await doPage($)
let a
// keep following next links
while(a = $('[rel=next]')[0]){
url = new URL($(a).attr('href'), url).href
response = await request(url)
$ = cheerio.load(response)
await doPage($)
}
})()