使用 data-v-xxxxxxxx 识别 html 结构并使用 selenium 压缩它们

Identifying html structures with data-v-xxxxxxxx and pressing them using selenium

正在尝试识别网站上的 javascript 按钮并按下它以扩展页面。

问题中的website是基本搜索后的腾讯应用商店。页面底部是一个标题为“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=%25E7%2594%25B5%25E5%25BD%25B1'

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 中实现,也无助于按下按钮。接下来我尝试在 driver 中找到元素并使用 .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

但所有 return 都出现相同的错误:'NoSuchElementException'

您的选择不起作用,因为它们没有指向 <a>

  • 这个按 class 名称选择,您尝试单击包含您的 <a>:

    <div>
    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 但它是标签、属性和 class:

    的混合体
    driver.find_element_by_class_name('a.load-more-new.load-more-btn-new[data-v-33600cb4]').click()
    

如何修复?

Select 你的元素更具体,更像你的第二个方法:

driver.find_element_by_css_selector('.load-more-btn-new a').click()

driver.find_element_by_css_selector('a[data-v-33600cb4]').click()

注:

在使用较新的 selenium 版本时,您将收到弃用警告:find_element_by_ 命令已弃用。请使用 find_element()*

from selenium.webdriver.common.by import By
driver.find_element(By.CSS_SELECTOR, '.load-more-btn-new a').click()