python - 使用 Selenium 获取数据
问题描述
我正在学习 Python,我的第一个项目是使用 Selenium 从 NFL 网站获取数据。我在添加数据的循环中遇到了一些问题,然后单击下一个按钮直到结束。出现的错误信息是这样的:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method": "xpath", "selector": "// * [@ title="下一页"]"}(会话信息: 铬 = 89.0.4389.114)
另外,我不知道这段代码是否会将数据添加到我的数据框中。我做错了什么或缺少什么?
# -*- encoding: utf-8 -*-
import time
import requests
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import json
from selenium.common.exceptions import TimeoutException
colunas =['Player','Pass Yds','Yds/Att','Att','Cmp','TD','INT','Rate','1st','1st%','20+','40+','Lng','Sck','SckY']
qb=pd.DataFrame()
url = "https://www.nfl.com/stats/player-stats/"
option = Options
option.headless= True
driver = webdriver.Chrome(executable_path='C:\Program Files\chromedriver.exe')
driver.get(url)
next_link = driver.find_element_by_xpath('//*[@title="Next Page"]')
while True:
element = driver.find_element_by_xpath("//div[@class='d3-o-table--horizontal-scroll']//table")
html_content = element.get_attribute('outerHTML')
time.sleep(3)
soup = BeautifulSoup(html_content,'html.parser')
table = soup.find(name='table')
df_full = pd.read_html( str(table))[0]
df1= df_full[['Player','Pass Yds','Yds/Att','Att','Cmp','TD','INT','Rate','1st','1st%','20+','40+','Lng','Sck','SckY']]
qb = pd.concat([df1])
try:
next_link = driver.find_element_by_xpath('//*[@title="Next Page"]')
next_link.click()
except ModuleNotFoundError:
break
driver.quit()
解决方案
try:
next_link = driver.find_element_by_xpath('//*[@title="Next Page"]')
next_link.click()
except NoSuchElementException:
break
只需抓住错误并打破。
进口
from selenium.common.exceptions import NoSuchElementException
推荐阅读
- kubernetes - 如何在普罗米修斯上获得每秒保存指标?
- php - 我在使用 cURL 登录我的 wordpress 网站时遇到问题
- scala - Spark - 如何处理更新
- robotframework - 将列表传递给机器人框架中的 python 库
- tesseract - 从图片中获取 Tesseract 中的空结果,但从上述图片的屏幕截图中获得了良好的结果
- python - Pandas 将日期时间对象类型转换为日期时间
- mysql - MySQL trigger after update to insert in audit table
- python-3.x - 如何使用 Ansible 2.9.2 python API 执行任务?
- java - 如何在 Kotlin/Java 中对 Numpy 数组(Python)进行 base64 解码?
- go - go中使用channel实现重试机制