我正在尝试从博彩网站进行一些网络抓取:
作为该过程的一部分,我必须单击左侧“收藏夹”部分下的不同按钮来选择不同的比赛。
我们以 ENG Premier League 按钮为例。我将该按钮标识为:
(来源:666kb.com)
XPath 为://*[@id="SportMenuF"]/div[3]
,ID 为 91。
我的点击按钮的代码如下:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
chrome_path = "C:\Python27\Scripts\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
driver.get("URL Removed")
content = driver.find_element_by_xpath('//*[@id="SportMenuF"]/div[3]')
content.click()
不幸的是,当我运行脚本时,我总是收到此错误消息:
"no such element: Unable to locate element:
{"method":"xpath","selector":"//*[@id="SportMenuF"]/div[3]"}"
我尝试了不同的标识符,例如 CCS 选择器、ID 以及如上例所示的 Xpath。我也尝试使用等待和显式条件。这些都不起作用。
我还尝试从网站上抓取一些值,但没有成功:
from selenium import webdriver
from selenium.webdriver.common.by import By
chrome_path = "C:\Python27\Scripts\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
driver.get("URL removed")
content = driver.find_elements_by_class_name('price-val')
for entry in content:
print entry.text
同样的问题,什么也没有显示。
该网站嵌入了来自不同网站的 iframe。这可能是我的问题的原因吗?我也尝试直接从 iframe URL 进行抓取,但这也不起作用。
如有任何建议,我将不胜感激。
最佳答案
有时元素要么隐藏在 iframe 后面,要么尚未加载
对于 iframe 检查,请尝试:
driver.switch_to.frame(0)
对于等待检查,请尝试:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, '-put the x-path here-')))
关于Python 2.7 Selenium 网站上没有这样的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54083452/