Improve TradingView layout loading with better debugging and selection logic

- Added comprehensive layout menu item detection with multiple selectors
- Implemented debug screenshots for layout menu and after layout changes
- Added better error handling and logging for layout selection
- Improved text matching with exact and partial match strategies
- Added fallback comprehensive search with direct click functionality
- Fixed TypeScript issues with element handle clicking
This commit is contained in:
root
2025-07-09 14:45:04 +02:00
parent 06842efbbd
commit b2d02cd716
6 changed files with 207 additions and 64 deletions

View File

@@ -306,50 +306,72 @@ export class TradingViewCapture {
if (layoutButton) {
await layoutButton.click()
console.log('Clicked layout button')
await new Promise(res => setTimeout(res, 1000))
// Look for search input or layout items
const searchSelectors = [
'input[name="search"]',
'input[placeholder*="search" i]',
'input[type="search"]',
'input[data-name="search"]'
// Wait longer for the layout menu to appear
await new Promise(res => setTimeout(res, 2000))
// Take a debug screenshot of the layout menu
const debugMenuPath = path.resolve(`debug_layout_menu_${layout.replace(/\s+/g, '_')}.png`) as `${string}.png`
await page.screenshot({ path: debugMenuPath })
console.log('Layout menu screenshot saved:', debugMenuPath)
// Look for layout menu items with more specific selectors
const layoutItemSelectors = [
`[data-name="chart-layout-list-item"]`,
`[data-testid*="layout"]`,
`.layout-item`,
`[role="option"]`,
`[role="menuitem"]`,
`.tv-dropdown-behavior__item`,
`.tv-menu__item`,
`li[data-value*="${layout}"]`,
`div[data-layout-name="${layout}"]`
]
let searchInput = null
for (const selector of searchSelectors) {
let layoutItem = null
let foundMethod = ''
let foundElement = false
// Try to find layout item by exact text match first
for (const selector of layoutItemSelectors) {
try {
searchInput = await page.waitForSelector(selector, { timeout: 3000 })
if (searchInput) break
console.log(`Trying selector: ${selector}`)
const items = await page.$$(selector)
console.log(`Found ${items.length} items with selector: ${selector}`)
for (const item of items) {
const text = await page.evaluate(el => {
const element = el as HTMLElement
return (element.innerText || element.textContent || '').trim()
}, item)
console.log(`Item text: "${text}"`)
if (text && text.toLowerCase() === layout.toLowerCase()) {
layoutItem = item
foundMethod = `exact match with selector: ${selector}`
break
}
}
if (layoutItem) break
} catch (e) {
// Continue to next selector
console.log(`Error with selector ${selector}:`, e)
}
}
if (searchInput) {
console.log('Found search input, typing layout name...')
await searchInput.type(layout, { delay: 50 })
await new Promise(res => setTimeout(res, 2000))
// Try to find and click the layout item
const layoutItemSelectors = [
'[data-name="chart-layout-list-item"]',
'[data-testid*="layout-item"]',
'.layout-item',
'[role="option"]'
]
let layoutItem = null
// If no exact match, try partial match
if (!layoutItem) {
for (const selector of layoutItemSelectors) {
try {
const items = await page.$$(selector)
for (const item of items) {
const text = await page.evaluate(el => {
const element = el as HTMLElement
return element.innerText || element.textContent
return (element.innerText || element.textContent || '').trim()
}, item)
if (text && text.toLowerCase().includes(layout.toLowerCase())) {
layoutItem = item
foundMethod = `partial match with selector: ${selector}`
break
}
}
@@ -358,33 +380,104 @@ export class TradingViewCapture {
// Continue to next selector
}
}
if (layoutItem) {
await layoutItem.click()
console.log('Clicked layout item:', layout)
} else {
console.log('Layout item not found, trying generic approach...')
await page.evaluate((layout) => {
const items = Array.from(document.querySelectorAll('*'))
const item = items.find(el => el.textContent?.toLowerCase().includes(layout.toLowerCase()))
if (item) (item as HTMLElement).click()
}, layout)
}
} else {
console.log('Search input not found, trying to find layout directly...')
await page.evaluate((layout) => {
const items = Array.from(document.querySelectorAll('*'))
const item = items.find(el => el.textContent?.toLowerCase().includes(layout.toLowerCase()))
if (item) (item as HTMLElement).click()
}
// If still no match, try a more comprehensive search
if (!layoutItem) {
console.log('No layout item found with standard selectors, trying comprehensive search...')
const foundElement = await page.evaluate((layout) => {
const allElements = Array.from(document.querySelectorAll('*'))
// Look for elements that contain the layout name
const candidates = allElements.filter(el => {
const text = (el.textContent || '').trim()
return text && text.toLowerCase().includes(layout.toLowerCase())
})
console.log('Found candidates:', candidates.map(el => ({
tag: el.tagName,
text: el.textContent?.trim(),
classes: el.className
})))
// Prioritize clickable elements
const clickable = candidates.find(el =>
el.tagName === 'BUTTON' ||
el.tagName === 'A' ||
el.hasAttribute('role') ||
el.classList.contains('item') ||
el.classList.contains('option') ||
el.classList.contains('menu')
)
if (clickable) {
(clickable as HTMLElement).click()
return true
}
// Fall back to exact text match
const exactMatch = candidates.find(el =>
(el.textContent || '').trim().toLowerCase() === layout.toLowerCase()
)
if (exactMatch) {
(exactMatch as HTMLElement).click()
return true
}
return false
}, layout)
}
await new Promise(res => setTimeout(res, 4000))
console.log('Layout loaded:', layout)
if (foundElement) {
foundMethod = 'comprehensive search with click'
console.log(`Found and clicked layout item "${layout}" using: ${foundMethod}`)
}
}
if (layoutItem) {
console.log(`Found layout item "${layout}" using: ${foundMethod}`)
await layoutItem.click()
console.log('Clicked layout item:', layout)
// Wait for layout to actually load
await new Promise(res => setTimeout(res, 5000))
// Take a screenshot after layout change
const debugAfterPath = path.resolve(`debug_after_layout_${layout.replace(/\s+/g, '_')}.png`) as `${string}.png`
await page.screenshot({ path: debugAfterPath })
console.log('After layout change screenshot saved:', debugAfterPath)
} else if (foundElement && foundMethod === 'comprehensive search with click') {
console.log('Layout item was clicked via comprehensive search')
// Wait for layout to actually load
await new Promise(res => setTimeout(res, 5000))
// Take a screenshot after layout change
const debugAfterPath = path.resolve(`debug_after_layout_${layout.replace(/\s+/g, '_')}.png`) as `${string}.png`
await page.screenshot({ path: debugAfterPath })
console.log('After layout change screenshot saved:', debugAfterPath)
} else {
console.log('Layout item not found with any method')
// List all text content on the page for debugging
const allTexts = await page.evaluate(() => {
const elements = Array.from(document.querySelectorAll('*'))
return elements
.map(el => (el.textContent || '').trim())
.filter(text => text && text.length > 0 && text.length < 100)
.slice(0, 50) // Limit to first 50 for debugging
})
console.log('Available texts on page:', allTexts)
}
} else {
console.log('Layout button not found, skipping layout loading')
}
console.log('Layout loading completed for:', layout)
} catch (e: any) {
const debugLayoutErrorPath = path.resolve('debug_layout_error.png') as `${string}.png`
const debugLayoutErrorPath = path.resolve(`debug_layout_error_${layout.replace(/\s+/g, '_')}.png`) as `${string}.png`
await page.screenshot({ path: debugLayoutErrorPath })
console.error('TradingView layout not found or could not be loaded:', e)
console.log('Continuing without layout...')