我在 32 位 Windows 机器上使用 Python 2.7。
我正在尝试将物种数据输入 http://explorer.natureserve.org并检索结果,但我很难理解如何去做。不用说,我对 Python 比较陌生。
我有以下代码:
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://explorer.natureserve.org")
assert "NatureServe" in driver.title
SciName = driver.find_element_by_name('searchSciOrCommonName')
SciName.send_keys("Arabis georgiana")
SciName.send_keys(Keys.RETURN)
assert "No results found." not in driver.page_source
以上有效,但现在我需要在结果页面上选择元素 Arabis georgiana,这会将我带到另一个页面。如何将结果页面返回到 Python 中并重定向到我真正想要的页面?
请您参考如下方法:
您需要这样设置 searchSciOrCommonName 字段值:
br.form = list(br.forms())[0]
br.form['searchSciOrCommonName'] = 'butterfly'
response = br.submit()
然后,您可以通过例如 BeautifulSoup 解析 HTML 响应:
from bs4 import BeautifulSoup
soup = BeautifulSoup(response)
for item in soup.select('table[border="1"] > tr i')[1:]:
print(item.text.strip())
这将打印:
Aglais io
Callophrys mossii hidakupa
Callophrys mossii marinensis
Cercyonis pegala incana
...
Psora nipponica
Flowering Plants
Asclepias tuberosa
