2017-03-07 1 views
2

Selenium으로 URL 목록을 생성하려고합니다. 사용자는 계측기가있는 브라우저를 탐색하고 마지막으로 방문한 URL 목록을 만들길 바랍니다.Selenium Python을 사용하여 URL 목록 생성하기

속성 "current_url"이 도움이 될 수 있지만 사용자가 링크를 클릭했음을 알 수있는 방법을 찾지 못했습니다.

In [117]: from selenium import webdriver 

In [118]: browser = webdriver.Chrome() 

In [119]: browser.get("http://stackoverflow.com") 

--> here, I click on the "Questions" link. 

In [120]: browser.current_url 

Out[120]: 'http://stackoverflow.com/questions' 

--> here, I click on the "Jobs" link. 

In [121]: browser.current_url 

Out[121]: 'http://stackoverflow.com/jobs?med=site-ui&ref=jobs-tab' 

감사합니다. 정말 사용자가 셀레늄에 무엇을하고 있는지 모니터링 할 수있는 공식적인 방법이 없습니다

답변

2

, 감사합니다. 당신이 정말로 할 수있는 유일한 일은 운전자를 시작한 다음 계속적으로 driver.current_url을 점검하는 루프를 돌리는 것입니다. 그러나, 나는이 루프를 종료하는 가장 좋은 방법은 당신의 사용법이 무엇인지 모르기 때문에 내가 모르는 것이다. 어쩌면 같은 시도 :이 루프를 종료하는 방법에 대한 어떤 생각을 가지고 있지 않은 경우, 내가 좋을 것

from selenium import webdriver 


urls = [] 

driver = webdriver.Firefox() 

current = 'http://www.google.com' 
driver.get('http://www.google.com') 
while True: 
    if driver.current_url != current: 
     current = driver.current_url 

     # if you want to capture every URL, including duplicates: 
     urls.append(current) 

     # or if you only want to capture unique URLs: 
     if current not in urls: 
      urls.append(current) 

을 하나 루프를 중단하는 URL로 이동 사용자와 같은 http://www.endseleniumcheck.com 및 추가

from selenium import webdriver 


urls = [] 

driver = webdriver.Firefox() 

current = 'http://www.google.com' 
driver.get('http://www.google.com') 
while True: 
    if driver.current_url == 'http://www.endseleniumcheck.com': 
     break 

    if driver.current_url != current: 
     current = driver.current_url 

     # if you want to capture every URL, including duplicates: 
     urls.append(current) 

     # or if you only want to capture unique URLs: 
     if current not in urls: 
      urls.append(current) 

또는 교묘 해지기를 원할 경우 사용자가 브라우저를 종료 할 때 루프를 종료 할 수 있습니다. 당신은 psutil 라이브러리 (pip install psutil)와 프로세스 ID를 모니터링하여이 작업을 수행 할 수 있습니다 :

from selenium import webdriver 
import psutil 


urls = [] 

driver = webdriver.Firefox() 
pid = driver.binary.process.pid 

current = 'http://www.google.com' 
driver.get('http://www.google.com') 
while True: 
    if pid not in psutil.pids(): 
     break 

    if driver.current_url != current: 
     current = driver.current_url 

     # if you want to capture every URL, including duplicates: 
     urls.append(current) 

     # or if you only want to capture unique URLs: 
     if current not in urls: 
      urls.append(current) 
+0

대단히 감사합니다! 그것은 할 것이다. 개인적으로 브라우저 종료를 처리하기 위해 마침내 try/catch 구조를 사용했습니다 (예외 발생). 그것은 깨끗하지는 않지만 나는하려고하는 것에 충분하다. – reike

관련 문제