Python Selenium 屏幕抓取
我正在尝试从一个网站抓取数据(下面是代码片段)
这个网站需要输入一些信息,然后跳转到第二个页面,再输入更多信息,最后显示一个表格。我在这个步骤上遇到了问题:
driver.find_element_by_xpath("//select[@id='agencies']/option[@value='13156']").click()
我收到的错误信息是:
selenium.common.exceptions.NoSuchElementException: Message: 'Unable to locate element:
这很奇怪,因为我确实看到了那个元素(注释掉的显示ID)。有没有人能帮帮我或者给点建议?
(我尝试过使用requests和RoboBrowser,但似乎无法让POST请求正常工作,也失败了)
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()
更新 -- 下面的代码在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()
1 个回答
1
在ID为agencies
的下拉框中,没有值为13156
的选项。这个下拉框的值范围是从102
到522
,你可以通过打印出来查看这些值:
[element.get_attribute('value') for element in driver.find_elements_by_xpath('//select[@id="agencies"]/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')