问题
Please, advise on how to open a link in a new tab with Python selenium Chrome Webdriver. So, I am not asking how to simply open a new tab, nor on how to open a new tab with Firefox.
This one opens the same page in a new tab:
first_link.send_keys(Keys.CONTROL + Keys.ENTER)
This one too:
first_link.send_keys(Keys.CONTROL + Keys.ENTER)
alecxe answer to this question does not work since, I cannot get an url a link is pointing at. I need to simply emulate Right-mouse-click > "Open link in a new tab".
Update
The problem turns out to be with the website https://www.pagesjaunes.fr itself. For some reason it give wrong urls for its entries in search results. For instance for element:
//*[@id="bi-bloc-0437413413085060110003C0001"]/div[2]/header/div[1]/div/h2/a[2]
Therefore, when the link of this element is attempted to be accessed via Selenium or requests, it redirects to the page of the search results itself. In light of this I decided to use a different approach to solving the issue.
Therefore I decided to abandon the approach of opening the link in a new tab.
回答1:
try this :
driver.find_element_by_tag_name("body").send_keys(Keys.COMMAND + 't')
回答2:
Below works for me great
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://tarunlalwani.com/post/")
action = ActionChains(driver)
elem = driver.find_element_by_link_text("How To Debug Nginx Reverse Proxy Issues")
action\
.move_to_element(elem)\
.key_down(Keys.SHIFT)\
.click(elem)\
.key_up(Keys.SHIFT)\
.perform()
driver.quit()
来源:https://stackoverflow.com/questions/46015904/how-to-open-a-link-in-a-new-tab-with-python-selenium-chromedriver