我正在尝试创建一个收集一些数据的应用程序。我在 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/