gpt4 book ai didi

python - 如何使用 selenium python 抓取雅虎财经搜索自动建议结果?

转载 作者:行者123 更新时间:2023-12-01 09:26:23 25 4
gpt4 key购买 nike

我正在尝试使用 selenium python 在雅虎财经上自动搜索。当我输入一些单词时,会弹出一个建议,就像谷歌建议一样。

https://finance.yahoo.com/

我发现一个带有xpath的列表元素应该是yahoo提出的建议:

//*[@id="search-assist-input"]/div[2]/ul

似乎建议内容隐藏在这个列表中,但它是不可见的,我的意思是当我点击展开它时,它就消失了。我不知道 Firefox 或 Chrome 中是否存在某种“始终展开节点”,但这些元素似乎很难到达。我尝试获取该元素下的所有子元素,但显示找不到元素:

from chrome_driver.chrome import Chrome

driver = Chrome().get_driver()
driver.get('https://finance.yahoo.com/')
driver.find_elements_by_xpath("//div[@id='search-assist-input']/div/input")[0].send_keys('goog')
x = driver.find_elements_by_xpath("//div[@data-reactid='56']/ul[@data-reactid='57']/*")

如何从搜索框中找到这些自动建议?

最佳答案

提取与搜索文本相关的自动建议,例如GOOGhttps://finance.yahoo.com/搜索框中,您必须诱导WebDriverWait自动建议可见,您可以使用以下解决方案:

  • 代码块:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC

    options = Options()
    options.add_argument("start-maximized")
    options.add_argument("disable-infobars")
    options.add_argument("--disable-extensions")
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\ChromeDriver\chromedriver_win32\chromedriver.exe')
    driver.get('https://finance.yahoo.com/')
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='p']"))).send_keys("goog")
    yahoo_fin_auto_suggestions = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//input[@name='p']//following::div[1]/ul//li")))
    for item in yahoo_fin_auto_suggestions :
    print(item.text)
  • 控制台输出:

    GOOG
    Alphabet Inc.Equity - NASDAQ
    GOOGL
    Alphabet Inc.Equity - NASDAQ
    GOOGL-USD.SW
    AlphabetEquity - Swiss
    GOOGL180518C01080000
    GOOGL May 2018 call 1080.000Option - OPR
    GOOG.MX
    Alphabet Inc.Equity - Mexico
    GOOG180525C01075000
    GOOG May 2018 call 1075.000Option - OPR
    GOOG180518C00720000
    GOOG May 2018 call 720.000Option - OPR
    GOOGL180518C01120000
    GOOGL May 2018 call 1120.000Option - OPR
    GOOGL.MX
    Alphabet Inc.Equity - Mexico
    GOOGL190621C01500000
    GOOGL Jun 2019 call 1500.000Option - OPR

关于python - 如何使用 selenium python 抓取雅虎财经搜索自动建议结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50355120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com