Python selenium scrape tradingview交易列表

2024-10-01 07:15:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从这个TradingView图表(https://www.tradingview.com/chart/lUsimB6z/)中抓取交易列表,但不知道从哪里开始。我先尝试了Selenium,但向下滚动时会加载表,这给我带来了一个问题。一般来说,我对Selenium和Python都是新手。任何帮助都将不胜感激。多谢各位


Tags: httpscom列表wwwseleniumchart图表交易
2条回答

如果你想缩短很短的时间(1s,5s),以防有人对此感兴趣。上述方法会产生问题,因为网站每10秒更新一次。我发现的方式如下所述:

  1. 使用chrome或brave
  2. 添加自动查看扩展名
  3. 它将在Strategy tester中添加一个名为“Export”的新选项卡
  4. 使用selenium单击该按钮将策略结果保存到剪贴板,然后将其粘贴到数据框中
  5. 导出到csv

下面是代码示例:

#click the Strategy tester tab so that the button is visible
c = driver.find_element_by_xpath('//*[@id="footer-chart-panel"]/div[1]/div[1]/div[4]/div/span')
driver.execute_script("$(arguments[0]).click();", c)

#click the Export button
z = driver.find_element_by_xpath('//li[@class="autoview-backtesting-export"]')
driver.execute_script("$(arguments[0]).click();", z)

如果其中任何一项失败,请尝试添加一个循环(0-5),并将操作放入循环中。其余的都与熊猫有关

#copy the clipboard into dataframe    
a = pd.read_clipboard(sep='\t', usecols=[]) 

因此,启动器代码如下所示:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

第一步是创建一个webdriver对象

chrome_options = Options()
# Stops the UI interface (chrome browser) from popping up
# chrome_options.add_argument(" headless") 
driver = webdriver.Chrome(executable_path='/path/to/chrome_driver', options=chrome_options)

使用URL启动浏览器

page_url = "https://www.tradingview.com/chart/lUsimB6z/"
driver.get(page_url)

driver元素包含可用于从html获取元素的方法。 使用driver.page_source可以获得完整的页面源代码。如果需要,只需使用soup = BeautifulSoup(driver.page_source, "html.parser")即可切换到BeautifulSoup

可以对driver对象使用的一些方法有:

driver.find_element_by_tag_name(tag_name)
driver.find_element(s)_by_class_name(class_name)
driver.save_screenshot()
etc...

这个link解释了如何使用driver对象在浏览器上模拟滚动来获取表数据

最后,

driver.quit()

您需要将chromedriver放置在'/path/to/chrome_driver'才能让selenium正常工作

相关问题 更多 >