python - Python + Selenium:网页抓取
问题描述
我正在尝试使用 Selenium 从网站中提取一些信息,下面是该网站的链接: http ://www.ultimatetennisstatistics.com/playerProfile?playerId=4742 我想要获取的信息是球员统计数据,位于下拉按钮“统计”,带您进入另一个 页面Ultimatetennisstatistics.com/playerProfile?playerId=4742
并给我一个错误:
NoSuchElementException: no such element:
Unable to locate element: {"method":"css selector","selector":"#playerPills > li.dropdown.active.open > ul > li.active"}
(Session info: chrome=67.0.3396.99)
(Driver info: chromedriver=2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e),platform=Windows NT 6.3.9600 x86_64)
下面是我的代码:
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.ultimatetennisstatistics.com/playerProfile?playerId=4742")
soup = BeautifulSoup(driver.page_source,"lxml")
bm = driver.find_element_by_css_selector('#playerPills > li.dropdown.active.open > ul > li.active')
bm.click()
有人可以告诉我们如何让玩家的统计页面使用 Selenium 打开并提取表格中的信息吗?
解决方案
如果您检查页面的 html 源代码,则可以直接访问要单击的按钮的 CSS id。使用 selenium,您可以通过它的 id 找到按钮,driver.find_element_by_id('statisticsPill')
然后单击它以显示表格。
加载后,您可以解析表格以获取所需的数据。
例子:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.ultimatetennisstatistics.com/playerProfile?playerId=4742")
try:
# Fist click on the dropdown
dropdown = driver.find_element_by_xpath("//a[@id='statisticsPill']/../../..")
dropdown.click()
# Then click on the statistics button
bm = driver.find_element_by_id('statisticsPill')
bm.click()
except NoSuchElementException as e:
# Do error handling when cannot find the button
编辑:您必须先单击下拉菜单才能使按钮可见,然后单击它。
推荐阅读
- javascript - 在 Javascript 文件中使用带有 JSON 数据的大小写切换
- python - keras model.save() 引发 NotImplementedError
- regex - 用完 Perl 的命令管道在 sed 前置路径时失败
- node.js - req.handle.writev 不是函数
- angular - 错误 TS1192:模块 @types/lodash/index 没有默认导出
- ios - 我想在 Swift UIPickerView 中保存一个选定的选项
- python - 在python中清除STDOUT中的当前行
- php - Codeigniter - 显示和编辑记录的最后一个 ID
- android-studio - ViewModelProviders.of(活动)错误
- docker - Vagrant 上的 Docker0 问题