javascript - 无法使用 Python scrapy 和 Selenium 从 javascript 网页中选择元素

标签 javascript python-2.7 selenium scrapy screen-scraping

我正在尝试创建一个收集一些数据的应用程序。我在 Windows 10 上使用 Python 2.7 以及 Scrapy 和 Selenium。我之前只使用几个网页完成了此操作,但是,我无法选择或单击以下网站中的按钮。

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

无法点击标有“搜索许可/投诉”的按钮

我使用 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"]"}

我添加了所有 sleep 和等待等,以确保在尝试选择之前页面已完全加载。我还尝试选择链接文本以及其他选择元素的方法。不知道为什么这个方法在这个页面上不起作用,而它在其他页面上对我有用。运行代码时,WebDriver 确实在我的屏幕上打开页面,并且我看到页面已加载,等等。

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

最佳答案

目标链接位于 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() 切换回来

关于javascript - 无法使用 Python scrapy 和 Selenium 从 javascript 网页中选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41155362/

相关文章:

python - PySide2 无法通过基本示例正确关闭

java - 使用同一 WebDriver 对象执行多个 JUnit 测试

javascript - 使用 JavaScript、JQuery 从网页中抓取评论

javascript - 如何在 mousedown、mousemove 上覆盖默认的 "text"光标?

javascript - 功能未达到

javascript - Chartjs 如何将垂直线保持在水平标尺线下方?

python-3.x - 没有名为套接字的模块

python - 忽略 os.listdir() 中的目录

vb.net - Selenium:使用 chrome 驱动程序将文件下载到特定文件夹

javascript - 在 jQuery 中匹配标签和字符串