python - 在 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 无头运行这段代码。请帮忙。
解决方案
一些网站在看到您的“无头”用户代理时表现不同。
尝试将您的用户代理更改为 Chrome 并查看它是否有效。
options.add_argument("""user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)""")
推荐阅读
- thingsboard - 按日期/时间安排操作
- windows - 如何使用 powershell 获取故障转移集群卷信息?
- powerbi - Power BI 报告服务器 - 门户管理员功能
- c# - .NET 未知主机名异常,但 nslookup 有效
- php - Messenger Chatbot:在实现人工交接协议的同时跟踪用户与机器人的聊天历史
- jakarta-ee - cqrs:在服务之间共享命令和事件语义
- functional-programming - 如何在 OCaml 中创建一个反转 int 列表的函数?
- java-8 - Java 8 Stream 类的动态过滤字段
- c++ - 如何在 C++ 中的函数内声明外部 C 函数?
- python - 每秒运行一个函数并与前一秒的值进行比较。