我正在尝试屏幕抓取一个网站(下面的代码段)

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

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


我得到的错误是:

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


这很奇怪,因为我确实看到了该元素(注释为Display 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()

最佳答案

在具有option id的13156中没有具有select值的agencies。从102522的值,可以通过打印看到它们:

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


另外,不要使用option查找value,而是使用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')

关于python - Python Selenium屏幕抓取,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24111681/

10-11 19:57