首页 > 解决方案 > Python Selenium,javascript按钮永远不会完成加载

问题描述

我正在做一个简单的硒脚本来获取此页面中的所有产品:https ://www.bauducco.com.br/produtos/ 。

我刚刚创建了这段代码来尝试打开页面并单击红色按钮以加载更多产品:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC
import time 

driver = webdriver.Firefox(executable_path=r'mypath')
driver.get('http://www.bauducco.com.br/produtos/')

button = driver.find_element_by_xpath(
                 '/html/body/div[1]/div/section/div[2]/span/a')

driver.execute_script("window.scrollTo(0, 1080)") 


button.click()
time.sleep(5)

这是所有的代码。我曾尝试使用 Google Chrome 和 fireFox 执行,但都没有奏效。该按钮只是继续加载,永远不会带来我的内容。即使我只是用硒打开页面并自己单击该按钮也不起作用。

一些想法发生了什么?也许是阻止机器人的技巧?

标签: pythonseleniumselenium-webdriver

解决方案


您应该添加 firefox webdriver 选项“--disable-web-security”,因为 webdriver 会阻止 CORS 请求:

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
firefox_options = Options()  
firefox_options.add_argument("--disable-web-security") 

driver = webdriver.Firefox(executable_path=r'mypath', 
firefox_options=firefox_options)
driver.get('http://www.bauducco.com.br/produtos/')

button = driver.find_element_by_xpath('/html/body/div[1]/div/section/div[2]/span/a')

button.click()

推荐阅读