JavascriptException:消息:javascript 错误:arguments[0].click 不是通过 Selenium 和 Python 使用 Arguments[0].click 的函数错误

rac*_*lll 4 javascript python selenium webdriver selenium-webdriver

我一直在抓取一些网站以获取进行网页抓取练习的位置。这段代码让我了解了酒店品牌的各个城市级别,但是每当我在代码中使用 driver.execute_script("arguments[0].click();", button) 时(如倒数第二行所示),我得到这个错误:

JavascriptException: Message: javascript error: arguments[0].click is not a function
Run Code Online (Sandbox Code Playgroud)

下面是我迄今为止编写的代码示例。

for state in state_links:
driver = Chrome(path_to_chrome_driver)
link = 'https://www.ihg.com/destinations/us/en/united-states/' + state.lower().replace(' ', '-')
driver.get(link)
city_links = driver.find_elements_by_xpath('//div[@class="countryListingContainer col-xs-12"]//ul//div//li//a//span')
city_links = [thing.text for thing in city_links]
driver.close()
for city in city_links:
    driver = Chrome(path_to_chrome_driver)
    link2 = 'https://www.ihg.com/destinations/us/en/united-states/' + state.lower().replace(' hotels', '').replace(' ', '-') + '/' + city.lower().replace(' ', '-')
    driver.get(link2)
    hotel_links = driver.find_elements_by_xpath('//div[@class="hotelList-detailsContainer"]//div//div//p//a')
    hotel_links = [elem.text for elem in hotel_links]
    driver.close()
    for hotel in hotel_links:
        driver = Chrome(path_to_chrome_driver)
        driver.get(link2)
        driver.implicitly_wait(15)
        driver.execute_script("arguments[0].click();", hotel)
        driver.implicitly_wait(10)
Run Code Online (Sandbox Code Playgroud)

Deb*_*anB 7

这个错误信息...

JavascriptException: Message: javascript error: arguments[0].click is not a function
Run Code Online (Sandbox Code Playgroud)

...意味着在使用时调用click()失败。arguments[0]execute_script()


有关这些步骤的更多信息将有助于我们构建规范的答案。但是,大概当您正在收集hotel_links之后:

driver.get(link2)
hotel_links = driver.find_elements_by_xpath('//div[@class="hotelList-detailsContainer"]//div//div//p//a')
Run Code Online (Sandbox Code Playgroud)

因此最初hotel_links包含WebElements。但在下一行中,您将使用elem.text覆盖列表 ,如下所示:hotel_links

hotel_links = [elem.text for elem in hotel_links]
Run Code Online (Sandbox Code Playgroud)

因此,hotel_links现在包含text类型的元素。

由于文本元素不支持click(),因此当您尝试click()通过 调用文本元素时execute_script(),您会看到上述错误。


解决方案

如果您需要酒店链接的文本,请将它们存储在单独的列表中,如下所示:

hotel_links_text = [elem.text for elem in hotel_links]
Run Code Online (Sandbox Code Playgroud)

参考

您可以在以下位置找到一些相关讨论: