使用Python和Selenium在html文档中选择超链接

2024-09-29 19:31:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从网站的文档中选择超链接,但不确定如何使用Selenium来选择它。你知道吗

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
names = 'Catostomus discobolus yarrowi'
driver = webdriver.Firefox()
driver.get("http://ecos.fws.gov/ecos/home.action")
SciName = driver.find_element_by_id('searchbox')
SciName.send_keys(names)
SciName.send_keys(Keys.RETURN)

上面的代码到达我感兴趣的页面,但不确定如何选择超链接。我有兴趣选择第一个超链接。感兴趣的html是

<a href="http://ecos.fws.gov/speciesProfile/profile/speciesProfile.action?spcode=E063" data-click="{&quot;p&quot;:1}">Zuni Bluehead Sucker (<strong>Catostomus discobolus</strong> yarrowi)</a>
</h4>
<div class='url'>ecos.fws.gov/speciesProfile/profile/speciesProfile.action?spcode=E063</div>


<span class='description'>
States/US Territories in which the Zuni Bluehead Sucker is known to or is believed to occur: Arizona, New Mexico; US Counties in which the Zuni ...
</span>
<ul class='sitelinks'></ul>
</div>

我猜我可以使用xpath查找元素,但一直未能成功完成。我希望总是选择第一个超链接。此外,超链接名称将根据输入的物种名称更改。你知道吗


Tags: fromimportdivdriverseleniumactionkeysclass
2条回答

我添加了以下代码:

SciName = driver.find_element_by_css_selector("a[href*='http://ecos.fws.gov/speciesProfile/profile/']")
SciName.click()

我应该更彻底地阅读selenium文档。你知道吗

试试这个:

SciName = driver.find_element_by_link_text("Zuni Bluehead Sucker")
SciName.click()

相关问题 更多 >

    热门问题