根据 Cannot pull data from pantip.com ,我尝试从 pantip.com 中提取数据,包括所有评论和每条评论的回复。
我在获取每条评论的回复文本时遇到问题。我使用 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/