【问题标题】:How to close newly constructed tab using selenium, chrome driver and python如何使用 selenium、chrome 驱动程序和 python 关闭新构建的选项卡
【发布时间】:2019-11-22 03:05:27
【问题描述】:

我正在尝试从网站上抓取数据,有一个 url 可以让我进入一个特定页面,我们有一些项目的链接,如果我点击这些链接,它会在一个新选项卡中打开,我可以提取来自那里的数据,

但提取数据后,我想关闭标签返回主页面并点击另一个链接。

我正在使用 selenium 和 chrome 网络驱动程序。我试过以下代码:

#links which lands me to a new tab
browser.find_element_by_xpath('//*[@id="data"]/div[1]/div[2]/a').click()

browser.switch_to.window(browser.window_handles[0])
browser.close() #it closes the main page, not the new tab I want
and following code,
browser.find_element_by_css_selector('body').send_keys(Keys.CONTROL + 'w')  #this code didn't work.

如何使用 selenium 和 python 关闭新建的标签页?

【问题讨论】:

    标签: python selenium selenium-webdriver web-scraping selenium-chromedriver


    【解决方案1】:

    你可以试试这个解决方案。

    # New tabs will be the last object in window_handles
    driver.switch_to.window(driver.window_handles[-1])
    
    # close the tab
    driver.close()
    
    # switch to the main window
    driver.switch_to.window(driver.window_handles[0])  
    

    参考:http://antlong.com/common-operations-working-with-tabs-in-webdriver/

    【讨论】:

      猜你喜欢
      • 2018-12-11
      • 1970-01-01
      • 2012-09-23
      • 2021-01-21
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 2022-12-21
      相关资源
      最近更新 更多