After opening the web in selenium, the user tried to get the url of the page opened by operating it.
from selenium import webdriver
import time
browser=webdriver.Chrome('chromedriver.exe')
browser.get('https://kakolog.jp/q/')
while True:
time.sleep(1)
print(browser.current_url)
After opening the web with the code above, I clicked on each thread, and it opened the page on a different tab, and I couldn't get the url for that page.
How can I get this url?
python selenium
If you want to get the URL of the link, you can extract the href
directly from <a target="_blank"...href="URL">
without clicking.
(See "#1. Read the first anchor from the element and get the URL" in the sample code.)
From there, driver.get
can be used to transition without pop-up.
Also, if you want to retrieve or manipulate the URL of a tab that pops up after clicking, you can activate any tab in driver.switch_to.window
.
(See "#2. Activate pop-up tab and get URL for active tab" in sample code)
Reference: How to get the URL "about:blank" from empty tab using selenium?
sample code:
from selenium import webdriver
import chromedriver_binary
import time
driver = webdriver.Chrome('chromedriver.exe')
url='https://kakolog.jp/q/'
driver.get(url)
time.sleep(1)
# Get leading 'boxContainer item' element
element=driver.find_element_by_class_name('boxContainer.item')
# 1. Read the first anchor from the element and get the URL
anchor=element.find_element_by_class_name('link')
print(anchor.get_attribute('href'))
# retain the main tab window handle
main_tab=driver.current_window_handle
# Click the anchor to pop up
anchor.click()
time.sleep(1)
# 2. Activate the pop-up tab and obtain the URL of the active tab
new_tab=[x for x driver.window_handles if x!=main_tab][0]
driver.switch_to.window(new_tab)
print(driver.current_url)
time.sleep(1)
# Close the Active Tab
driver.close()
time.sleep(1)
© 2024 OneMinuteCode. All rights reserved.