2016-11-23 159 views
0

我正在嘗試將Selenium與BeautifulSoup結合使用。更具體地說,我試圖點擊下拉菜單here中的鏈接NCAA Division I(最初它說的是Top 25)。Selenium Python無法找到_element_by_link_text

該鏈接的HTML標記看起來像這樣:

<li><a href="#" data-type="conference" data-week="null-null-null" data-group="50">NCAA Division I</a></li> 

對我來說,這似乎直截了當:driver.find_element_by_link_text('NCAA Division I').click()

這是因爲href="#",抑或是<a>標籤被嵌入在一個<li>標籤?

這裏發生了什麼:

(Pdb) driver.find_element_by_link_text('NCAA Division I').click() 
*** NoSuchElementException: Message: no such element: Unable to locate element: {"method":"link text","selector":"NCAA Division I"} 
    (Session info: chrome=54.0.2840.100) 
    (Driver info: chromedriver=2.25.426924 (649f9b868f6783ec9de71c123212b908bf3b232e),platform=Linux 4.4.0-45-generic x86_64) 

全碼:

import numpy as np 
import requests 
from bs4 import BeautifulSoup 
import re 
import datetime 
import os 
from selenium import webdriver 

scores_link = "http://www.espn.com/mens-college-basketball/scoreboard/_/date/20161122" 
r = requests.get(scores_link) 

driver = webdriver.Chrome() 
driver.get(scores_link) 
driver.find_element_by_link_text('NCAA Division I').click() 
soup = BeautifulSoup(driver.page_source) 

回答

0

自從 「我NCAA司」 纔會來鼠標懸停後,所以我們必須使用ActionChains硒(http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains

試試這個代碼,它會工作:

from selenium import webdriver 
from selenium.webdriver.common.action_chains import ActionChains 

driver = webdriver.Chrome() 
driver.maximize_window() 
driver.get('http://www.espn.com/mens-college-basketball/scoreboard/_/date/20161122') 

el2=driver.find_element_by_xpath("//header[@class='automated-header']//button[.='Top 25']") 
action = ActionChains(driver) 
action.move_to_element(el2).click().perform() 

driver.find_element_by_link_text('NCAA Division I').click()