Selenium无法提交评论

2024-10-01 07:25:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个脚本,允许我以编程方式向新闻网站提交评论。 我正在使用Selenium,这是我的纸条(与我尝试使用的链接完全一致):

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()

url = "https://www.delfi.lt/en/lifestyle/earth-day-events-for-the-spring-equinox.d?id=87005127"
driver.get(url)

# Clicking 'I agree' on a cookies banner:
cookies_ok = '//*[@id="c-right"]/a'
driver.find_element_by_xpath(cookies_ok).click()

# XPath list
anon = '//*[@id="comments-listing"]/div[2]/div/div[2]/div/ul/li[1]/span'
name = '//*[@id="inputDiv"]/div/form/input'
comment = '//*[@id="inputDiv"]/div/form/div[3]/div/textarea'
button = '//*[@id="inputDiv"]/div/form/div[4]/div[2]/button[1]'

# Click 'Anonymous' -> fill name and comment fields -> press PUBLISH
driver.find_element_by_xpath(anon).click()
driver.find_element_by_xpath(name).send_keys('name')
driver.find_element_by_xpath(comment).send_keys('comment')
driver.find_element_by_xpath(button).click()

一切正常,但当我执行最后一个命令时,我在网站上收到以下消息: enter image description here

“浏览器阻止或不支持cookie”。然而,当我自己在浏览器中执行相同的步骤时,cookie没有问题

关于如何防止这个错误有什么想法吗

谢谢


Tags: namedivformidbydrivercommentelement
2条回答

您可以优化代码,我假设您必须使用最新的二进制文件:

driver = webdriver.Chrome("C:\\Users\\***\\Desktop\\Selenium+Python\\chromedriver.exe")
driver.maximize_window()
wait = WebDriverWait(driver, 30)
driver.get("https://www.delfi.lt/en/lifestyle/earth-day-events-for-the-spring-equinox.d?id=87005127")
wait.until(EC.element_to_be_clickable((By.XPATH, "//*[@id='c-right']/a"))).click()
ActionChains(driver).move_to_element(wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "li.as-link:first-child")))).click().perform()
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.input-name"))).send_keys("denisafonin")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "textarea.input-message"))).send_keys("Your comment")
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.input-login"))).click()

试试这个

driver = webdriver.Chrome(executable_path=webdriver_manager.chrome.ChromeDriverManager().install())

这将安装最新的chrome浏览器并运行测试

您可能需要使用pip install webdriver-manager安装webdriver-manager

相关问题 更多 >