首页 > 解决方案 > 在 python selenium 无头模式下不会执行 for 循环

问题描述

如果不使用 selenium headless,下面的代码可以正常工作。但是在无头模式下,为什么 for 循环不会执行?

这是我的代码:-

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup


options = Options()
options.add_argument("--disable-notifications")
options.add_argument('headless')
driver = webdriver.Chrome(ChromeDriverManager().install(), chrome_options=options)
url = "https://www.justdial.com/Delhi/S-K-Premium-Par-Hari-Nagar/011PXX11-XX11-131128122154-B8G6_BZDET"
driver.get(url)
try:
   pop_up = WebDriverWait(driver, 30).until(
    EC.element_to_be_clickable((By.XPATH, '//*[@id="best_deal_detail_div"]/section/span')))
   pop_up.click()  # For disable pop-up
except TimeoutException:
   pass
while True:
   try:
      element = WebDriverWait(driver, 20).until(
        EC.element_to_be_clickable((By.XPATH, "//span[text()='Load More Reviews..']")))
      element.click()

   except TimeoutException:
      break
   except:
      pass

 soup = BeautifulSoup(driver.page_source, 'lxml')
 services = soup.find_all('span', {'class': "rName lng_commn"})
 for i in services:
      print(i.text)

我想用 selenium 无头运行这段代码。请帮忙。

标签: pythonpython-3.xseleniumselenium-webdriverbeautifulsoup

解决方案


一些网站在看到您的“无头”用户代理时表现不同。

尝试将您的用户代理更改为 Chrome 并查看它是否有效。

options.add_argument("""user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)""")

推荐阅读