試圖識別網站上的 javascript 按鈕并按下它以擴展頁面。
該網站是進行基本搜索后的騰訊應用商店。頁面底部是一個標題為“div.load-more-new”的按鈕,按下該按鈕將使用更多應用程式擴展頁面。
html如下
<div data-v-33600cb4="" class="load-more-btn-new" style="">
<a data-v-33600cb4="" href="javascript:void(0);">加載更多
<i data-v-33600cb4="" class="load-more-icon">
</i>
</a>
</div>
起初我以為我可以使用 BeautifulSoup 識別按鈕,但所有查找結果的呼叫都是空的。
from selenium import webdriver
import BeautifulSoup
import time
url = 'https://webcdn.m.qq.com/webapp/homepage/index.html#/appSearch?kw=%E7%94%B5%E5%BD%B1'
WebDriver = webdriver.Chrome('/chromedriver')
WebDriver.get(url)
time.sleep(5)
# Find using BeuatifulSoup
soup = BeautifulSoup(WebDriver.page_source,'lxml')
button = soup.find('div',{'class':'load-more-btn-new'})
[0] []
環顧四周后,很明顯,即使我可以在 BeuatifulSoup 中使用它,按下按鈕也無濟于事。接下來我嘗試在驅動程式中找到該元素并使用 .click()
driver.find_element_by_class_name('div.load-more-btn-new').click()
[1] NoSuchElementException
driver.find_element_by_css_selector('.load-more-btn-new').click()
[2] NoSuchElementException
driver.find_element_by_class_name('a.load-more-new.load-more-btn-new[data-v-33600cb4]').click()
[3] NoSuchElementException
但都回傳相同的錯誤:'NoSuchElementException'
uj5u.com熱心網友回復:
您的選擇將不起作用,因為它們沒有指向<a>.
這個按類名選擇,您嘗試單擊
<div>包含您的<a>:driver.find_element_by_class_name('div.load-more-btn-new').click()這個非常接近,但缺少
a選擇:driver.find_element_by_css_selector('.load-more-btn-new').click()這個嘗試
find_element_by_class_name但是是標簽,屬性和類的狂野組合:driver.find_element_by_class_name('a.load-more-new.load-more-btn-new[data-v-33600cb4]').click()
怎么修?
選擇更具體的元素,幾乎就像在第二個方法中一樣:
driver.find_element_by_css_selector('.load-more-btn-new a').click()
要么
driver.find_element_by_css_selector('a[data-v-33600cb4]').click()
筆記:
在使用較新的 selenium 版本時,您將收到 DeprecationWarning: find_element_by_命令已棄用。請使用 find_element()*
from selenium.webdriver.common.by import By
driver.find_element(By.CSS_SELECTOR, '.load-more-btn-new a').click()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/451812.html
