2014-06-08 114 views
1

我想屏幕刮网站(下段)Python的硒屏幕抓取

网站获取输入,导航到第二页,并需要更多的投入,最终显示的表。我不能在这一步:

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

我得到的错误是:

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

,因为我看到的元素(注释掉显示ID),这是奇怪的。请帮忙/指点吗?

(我想请求/ 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作品。我打算选择列表框中的所有选项并保存查询结果......感谢指针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() 
+0

您应使用名字,而不是数字。 – EL3PHANTEN

+0

谢谢Alecxe!现在起要BeautifulSoup读表.... 如果有人更优雅的方式做以上(使用请求或RoboBrowser)知道,请不要评论。非常感谢所有读者! – Arun

+0

@ user3720674你不需要'BeautifulSoup',我很确定'selenium'可以处理这种情况。如果您需要帮助,请考虑使用详细信息创建单独的SO问题。谢谢。 – alecxe

回答

1

没有optionselectagencies ID 13156值。有从102522值,可以通过印刷看到他们:

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

此外,而不是由value发现option S,通过文本使用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') 
+0

*脸掌* ....非常感谢!我会更新我的评论。 – Arun