Selenium Python无法find_element_by_link_text

时间:2016-11-23 01:16:53

标签: python selenium

我正在尝试将Selenium与BeautifulSoup结合使用。更具体地说,我正在尝试点击下拉菜单here中的链接NCAA Division I(最初说Top 25)。

链接的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)

1 个答案:

答案 0 :(得分:0)

自NCAA分部I&#34;只有鼠标悬停后才会出现,所以我们必须使用selenium的ActionChains(http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains

试试这段代码,它会起作用:

<style>
.div1, .div2 {
    width: 350px;
    height: 60px;
    padding: 10px;
    display:inline-block;
    border: 1px solid #aaaaaa;
}
</style>
<script>
function allowDrop(ev) {
    ev.preventDefault();
}

function drag(ev) {
    ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>

<div class="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<div class="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="http://www.w3schools.com/html/img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">