我正在尝试使用Puppeteer进行网络爬虫,所需的任务是单击单选按钮列表并从表中获取数据。单击每个单选按钮时,它将重新加载具有不同数据集的表。表格和单选按钮都在同一页面上。
但是,当我遍历这些输入并彼此执行QUERY="insert into table (field1, field2, field3) values ({}, {}, {})"
with open('input.txt', 'r') as inputfile:
readfile = inputfile.read()
inputlist = readfile.splitlines()
listafinal = []
for x in inputlist:
intermediate = x.split(' ')
cur.execute(QUERY.format(intermediate[0], intermediate[1], intermediate[2]))
# if error:
# log into the error file
# else:
# log into the success file
时,表上的数据集似乎无法正确刷新/重新加载。
这是我的实现方式:
click()
const url = THE_URL
const browser = await puppeteer.launch(constants.puppeteerOptions);
try {
const page = await browser.newPage();
await page.setUserAgent(constants.userAgent);
await page.goto(url);
await page.waitForSelector('div.sidePanel')
var inputs = await page.$$('div#radioButtons input')
var promises = []
for (let i=0; i < inputs.length; i++) {
const input = inputs[i]
const promise = getDataPromise(page, input)
promises.push(promise)
}
var dataset = await Promise.all(promises)
} catch (err) {
console.log("Puppeteer error", err);
return;
} finally {
await browser.close();
}
async function getDataPromise(page, input) {
const id = await page.evaluate(el => el.getAttribute('id'), input)
const categoryName = await page.evaluate(el => el.getAttribute('value'), input)
const selector = 'input#' + id
await page.evaluate((selector) => document.querySelector(selector).click(), selector),
await page.waitForNavigation()
const tableHtml = await page.$eval('table.dataTable', el => el.outerHTML)
console.log('---')
console.log(selector)
console.log(tableHtml)
const data = evaluateHtml(tableHtml, categoryName)
return data
}
语句始终打印单击最后一个单选按钮时加载的表,而console.log(tableHtml)
正确打印不同的console.log(selector)
id。 selector
看起来像这样,为了简洁起见:
console.log
分别单击其单选按钮时,应正确加载每个表。意见表示感谢,谢谢。