【问题标题】:Cannot select element from a javascript webpage using Python scrapy and Selenium无法使用 Python scrapy 和 Selenium 从 javascript 网页中选择元素
【发布时间】:2017-04-30 12:52:34
【问题描述】:

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

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"]"}

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

任何帮助将不胜感激。谢谢...

【问题讨论】:

    标签: javascript python-2.7 selenium scrapy screen-scraping


    【解决方案1】:

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

    【讨论】:

    • 安德森是天才。谢谢,解决了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 2020-08-08
    相关资源
    最近更新 更多