【问题标题】:Using Python to enter data into form and get data from results page使用 Python 将数据输入表单并从结果页面获取数据
【发布时间】:2015-02-05 21:41:25
【问题描述】:

我在 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 并重定向到我真正想要的页面?

【问题讨论】:

    标签: python web mechanize


    【解决方案1】:

    您需要这样设置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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      • 2017-09-16
      相关资源
      最近更新 更多