[英]How to open a link in a new tab with Python selenium ChromeDriver
Please, advise on how to open a link in a new tab with Python selenium Chrome Webdriver.请就如何使用 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.
所以,我不是在问如何简单地打开一个新标签,也不是在问如何用 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. alecxe 对这个问题的回答不起作用,因为我无法获得链接指向的 url。 I need to simply emulate Right-mouse-click > "Open link in a new tab".
我需要简单地模拟鼠标右键单击>“在新选项卡中打开链接”。
The problem turns out to be with the website https://www.pagesjaunes.fr itself.结果证明问题出在网站https://www.pagesjaunes.fr本身。 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.因此,当试图通过 Selenium 或请求访问此元素的链接时,它会重定向到搜索结果本身的页面。 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.因此我决定放弃在新标签页中打开链接的方法。
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()
试试这个:
driver.find_element_by_tag_name("body").send_keys(Keys.COMMAND + 't')
你首先需要“pip install keyboard”
keyboard.press("ctrl+t")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.