javascript - 无法使用 Selenium 单击按钮

标签 javascript python selenium selenium-webdriver beautifulsoup

根据 Cannot pull data from pantip.com ,我尝试从 pantip.com 中提取数据,包括所有评论和每条评论的回复。

enter image description here

我在获取每条评论的回复文本时遇到问题。我使用 selenium 单击按钮以获取其中的文本。但是,只有当我将页面滚动到按钮的位置时它才有效。

如果我不滚动,则会出现错误。

WebDriverException: unknown error: Element <a href="javascript:void(0)" class="reply see-more">...</a> is not clickable at point (518, 507). Other element would receive the click: <select class="dropdown-jump">...</select>
  (Session info: chrome=71.0.3578.98)
  (Driver info: chromedriver=2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387),platform=Windows NT 10.0.17134 x86_64)

有什么办法获取里面的数据吗?我需要滚动到按钮吗? 请推荐我。

import requests
import re
from bs4 import BeautifulSoup
from selenium import webdriver

chrome_path = r"C:\Users\user\Downloads\chromedriver_win32\chromedriver.exe"
url='https://pantip.com/topic/38372443'
driver = webdriver.Chrome(chrome_path)
driver.get(url)

content=driver.page_source
soup=BeautifulSoup(content,'lxml')  

#Click all buttons
for div in soup.find_all("div", id = lambda value: value and value.startswith("reply-comment-")):
    xPath =  '''//*[@id="''' + str(div['id']) + '''"]/a''' 
    button = driver.find_element_by_xpath(xPath).click()


# Get all comments   
text = list()    
for div in soup.find_all("div", id = lambda value: value and value.startswith("comment-")):
    if len(str(div.text).strip()) > 1:
        text.append(str(div.text).strip())
driver.quit()

最佳答案

页面底部有一个固定的导航面板,因此当您尝试单击按钮时,您实际上单击了该面板中的元素,这就是引发异常的原因...您可能需要

  • 滚动到所需按钮
  • 向下滚动一点
  • 点击按钮查看回复

    from selenium.webdriver.common.keys import Keys
    
    for reply in driver.find_elements_by_xpath('//div[starts-with(@id, "reply-comment-")]/a'):
        driver.execute_script('arguments[0].scrollIntoView();', reply)
        reply.send_keys(Keys.DOWN)
        reply.click()
    

关于javascript - 无法使用 Selenium 单击按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54035317/

相关文章:

javascript - tabBarOnPress 在 react native 的 react 导航选项卡中不起作用

javascript - 使用 jQuery 获取没有 CSS 类的特定元素

python - Flask 重定向上传的文件 - 对关闭的文件进行 I/O 操作

selenium - 使用 selenium webdriver 在自定义下拉列表中选择一个选项

python - 操作系统错误 : [Errno 8] Exec format error: 'geckodriver' when trying to open firefox using selenium in python

selenium - 隐式等待和显式等待之间的内部工作区别是什么

javascript - adonisjs 与 mysql 的迁移问题

javascript:在没有库的情况下保存字符/数字

javascript - 将 python 转换为 JavaScript

python - 如何从 python 代码构建 pyinstaller 规范文件