我使用這個Python 3代碼從網頁獲取一些下載網址,當網頁打開時,我想向元素發送一個點擊事件,并觸發生成下載網址,然后獲取下載網址,但現在我無法觸發單擊事件,顯示如下錯誤:
File "/Users/dolphin/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/212.5457.59/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevd.py", line 1483, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Users/dolphin/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/212.5457.59/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents "\n", file, 'exec'), glob, loc)
File "/Users/dolphin/source/reddwarf/backend/pydolphin/dolphin/biz/music/fetch.py", line 19, in <module>
driver.find_element(By.CSS_SELECTOR, "aplayer-list-download iconfont icon-xiazai").click()
File "/usr/local/anaconda3/envs/pydolphin/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 1244, in find_element
return self.execute(Command.FIND_ELEMENT, {
File "/usr/local/anaconda3/envs/pydolphin/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py", line 424, in execute
self.error_handler.check_response(response)
File "/usr/local/anaconda3/envs/pydolphin/lib/python3.9/site-packages/selenium/webdriver/remote/errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"aplayer-list-download iconfont icon-xiazai"}
(Session info: chrome=96.0.4664.55)
這是我觸發下載事件的代碼:
from selenium.webdriver.chrome.service import Service
from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
class FetchMusic:
def __init__(self):
print("fetch...")
if __name__ == '__main__':
s = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=s)
# driver.maximize_window()
driver.get('http://tool.liumingye.cn/music/?page=audioPage&type=migu&name=Unstoppable')
driver.implicitly_wait(5)
driver.find_element(By.CSS_SELECTOR, "aplayer-list-download iconfont icon-xiazai").click()
modal_body = driver.find_element(By.CLASS_NAME, "modal-body").get_attribute("href")
# results = driver.page_source
for result in modal_body:
print(result.text)
我該怎么做才能讓它發揮作用?
uj5u.com熱心網友回復:
您忘記.在類名稱之前添加類選擇器。
driver.find_element(By.CSS_SELECTOR, ".aplayer-list-download.iconfont.icon-xiazai").click()
下一行將不起作用
modal_body = driver.find_element(By.CLASS_NAME, "modal-body").get_attribute("href")
因為模態主體 div 沒有屬性呼叫href,所以如果你想提取模態主體 div 內的所有 URL,你可以使用 JavaScript 中的 querySelector API。見下文
urls = [a.get_attribute('href') for a in driver.execute_script('return document.querySelectorAll(".modal-body a[href*=\'http\']")')]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/367176.html
上一篇:選擇具有更改xpath的元素
