【问题标题】:Python Selenium Screen ScrapePython Selenium 屏幕抓取
【发布时间】:2014-07-29 11:39:41
【问题描述】:

我正在尝试对网站进行屏幕抓取(下面的 sn-p)

网站接受输入,导航到第二页并接受更多输入,最后显示一个表格。我在这一步失败了:

driver.find_element_by_xpath("//select[@id='agencies']/option[@value='13156']").click()

我得到的错误是:

selenium.common.exceptions.NoSuchElementException: Message: 'Unable to locate element: 

这很奇怪,因为我确实看到了元素(已注释掉显示 id)。请问有什么帮助/指点吗?

(我尝试了 requests/RoboBrowser -- 似乎无法让帖子正常工作,但在那里也失败了)

from selenium import webdriver
from selenium import selenium
from bs4 import BeautifulSoup

driver = webdriver.Firefox()
url = 'http://www.ucrdatatool.gov/Search/Crime/Local/OneYearofData.cfm'
driver.get(url)

driver.find_element_by_xpath("//select[@id='state']/option[@value='1']").click()
#driver.find_element_by_xpath("//select[@id='groups']/option[@value='8']").click()

driver.find_element_by_xpath("//input[@type='submit' and @value='Next']").click()
driver.implicitly_wait(5) # seconds

# Display id tags
#elementsAll = driver.find_elements_by_xpath('//*[@id]')
#for elements in elementsAll:
#    print("id: ", repr(elements))
#    print("idName: ",elements.get_attribute("id"))
#    driver.implicitly_wait(5) # seconds

driver.find_element_by_xpath("//select[@id='groups']/option[@value='2']").click()
driver.find_element_by_xpath("//select[@id='year']/option[@value=1986]").click()
driver.find_element_by_xpath("//select[@id='agencies']/option[@value='13156']").click()

更新 -- below 在 Selenium 上工作。我打算选择列表框中的所有选项并保存查询结果...感谢 Alecxe 的指点!

select = Select(driver.find_element_by_id('agencies'))
for options in select.options:
    select.select_by_visible_text(options.text)

select = Select(driver.find_element_by_id('groups'))
for options in select.options:
    select.select_by_visible_text(options.text)

driver.find_element_by_xpath("//select[@id='year']/option[@value=1985]").click()

driver.find_element_by_xpath("//input[@type='submit' and @value='Get Table']").click()

【问题讨论】:

  • 你应该使用名字,而不是数字。
  • 感谢亚历克西!现在开始到 BeautifulSoup 阅读表格......如果有人知道执行上述操作的更优雅的方式(使用请求或 RoboBrowser),请发表评论。再次感谢所有读者!
  • @user3720674 你不需要BeautifulSoup,我很确定selenium 会处理这个案子。如果您需要帮助,请考虑创建一个包含详细信息的单独 SO 问题。谢谢。

标签: python html selenium selenium-webdriver web-scraping


【解决方案1】:

selectagencies id 中没有option13156 值。有102522的值,打印出来就可以看到:

[element.get_attribute('value') for element in driver.find_elements_by_xpath('//select[@id="agencies"]/option')] 

另外,不要通过value 查找options,而是使用Select 并通过文本获取选项:

from selenium.webdriver.support.ui import Select

select = Select(driver.find_element_by_id('agencies'))
print select.options
select.select_by_visible_text('Selma Police Dept')

【讨论】:

    猜你喜欢
    • 2019-01-17
    • 2010-10-23
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 2011-02-20
    • 1970-01-01
    相关资源
    最近更新 更多