首页 > 解决方案 > 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 打开并提取表格中的信息吗?

标签: pythonseleniumscrape

解决方案


如果您检查页面的 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

编辑:您必须先单击下拉菜单才能使按钮可见,然后单击它。


推荐阅读