简体   繁体   English

使用 Python Selenium 4.1.0 获取页面上的所有链接

[英]get all links on a page with Python Selenium 4.1.0

I would like to find and visit all the links on a page using Python Selenium.我想使用 Python Selenium 查找并访问页面上的所有链接。 I am getting the following error.我收到以下错误。

Traceback (most recent call last): File "C:\Users\Acer\PycharmProjects\selenium-rpa\main.py", line 24, in print(elem.get_attribute("href")) AttributeError: 'str' object has no attribute 'get_attribute'.回溯(最后一次调用):文件“C:\Users\Acer\PycharmProjects\selenium-rpa\main.py”,第 24 行,在 print(elem.get_attribute("href")) AttributeError: 'str' object 有没有属性“get_attribute”。 Did you mean: ' getattribute '?你的意思是:' getattribute '?

My code:我的代码:

from selenium import webdriver
from datetime import datetime
import requests, urllib3
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service

PATH = Service("C:\chromedriver.exe")
url = "http://localhost/rpa_anomaly/test.php"
browser = webdriver.Chrome(service=PATH)
browser.get(url)

elems = browser.find_element(By.XPATH, "//a[@href]")
for elem in elems:
    print(elem.get_attribute("href"))

same problem here but my selenium version is newer.这里有同样的问题,但我的 selenium 版本更新。 so I can't use it like below所以我不能像下面那样使用它

elems = driver.find_elements_by_xpath("//a[@href]")
for elem in elems:
    print(elem.get_attribute("href"))

Fetch all href link using selenium in python 在 python 中使用 selenium 获取所有 href 链接

You can try with regular method of tagname您可以尝试使用标记名的常规方法

from selenium import webdriver
from webdriver_manager.microsoft import EdgeChromiumDriverManager

driver = webdriver.Edge(EdgeChromiumDriverManager().install())
driver.get("http://localhost/rpa_anomaly/test.php")
# identify elements with tagname <a>
lnks = driver.find_elements_by_tag_name("a")
# traverse list
for lnk in lnks:

    print(lnk.get_attribute("href"))
driver.quit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM