无法使用 Python scrapy 和 Selenium 来自 javascript 网页的 select 元素

Cannot select element from a javascript webpage using Python scrapy and Selenium

我正在尝试创建一个收集一些数据的应用程序。我在 Windows 10 上使用带有 Scrapy 和 Selenium 的 Python 2.7。我之前只用几个网页完成了这个,但是,我无法 select 或点击在以下网站的按钮上。

https://aca3.accela.com/Atlanta_Ga/Default.aspx

无法单击标有 "Search Permits/Complaints"

的按钮

我使用 Chrome 开发工具来检查 XPath 等

这是我正在使用的代码:

import scrapy
from selenium import webdriver

class PermitsSpider(scrapy.Spider):
  name = "atlanta"
  url = "https://aca3.accela.com/Atlanta_Ga/Default.aspx"

  start_urls = ['https://aca3.accela.com/Atlanta_Ga/Default.aspx',]

  def __init__(self):
    self.driver = webdriver.Chrome()
    self.driver.implicitly_wait(20)

  def parse(self, response):
    self.driver.get(self.url)

    time.sleep(15)
    search_button = self.driver.find_element_by_xpath('//*[@id="ctl00_PlaceHolderMain_TabDataList_TabsDataList_ctl01_LinksDataList_ctl00_LinkItemUrl"]')
    search_button.click()

当运行该代码时,出现以下错误:

NoSuchElementException:消息:没有这样的元素:无法定位元素:{"method":"xpath","selector":"//*@id="ctl00_PlaceHolderMain_TabDataList_TabsDataList_ctl01_LinksDataList_ctl00_LinkItemUrl"] "}

我添加了所有睡眠和等待等,以确保在尝试 selection 之前页面已完全加载。我还尝试 select Link 文本,以及 selecting 元素的其他方法。不知道为什么这个方法在这个页面上不起作用,而它对我适用于其他人。当 运行 代码时,WebDriver 会在我的屏幕上打开页面,我会看到页面已加载等。

如有任何帮助,我们将不胜感激。谢谢...

目标 link 位于 iframe 内,因此您必须切换到该框架才能处理嵌入的元素:

self.driver.switch_to_frame('ACAFrame')
search_button = self.driver.find_element_by_xpath('//*[@id="ctl00_PlaceHolderMain_TabDataList_TabsDataList_ctl01_LinksDataList_ctl00_LinkItemUrl"]')

您可能还需要使用 driver.switch_to_default_content()

切换回来