Skip to main content
 首页 » 编程设计

python之使用 Selenium Python 生成 URL 列表

2024年10月01日10lhb25

我正在尝试使用 Selenium 生成 URL 列表。 我希望用户在经过检测的浏览器中导航,并最终创建他访问过的 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' 

感谢任何提示!

谢谢,

请您参考如下方法:

并没有真正的官方方法来监控用户在 Selenium 中所做的事情。您真正能做的唯一一件事就是启动驱动程序,然后运行一个不断检查 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)