gpt4 book ai didi

python - Selenium Chrome 获取文本在 headless 模式下不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 21:18:43 25 4
gpt4 key购买 nike

当我使用 Chrome webdriver 在 headless 模式下运行 selenium 时,我遇到了奇怪的行为。到目前为止,我之前在 headless 模式下获取文本时没有遇到这个问题,它总是有效。

可重现的示例如下:

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

options = webdriver.ChromeOptions()
#options.add_argument('--headless')
#options.add_argument('--no-sandbox')

driver = webdriver.Chrome(chrome_options=options)

driver.get("https://www.zoom.com.br/ar-condicionado/todos")

wait = WebDriverWait(driver, 10)

stores = wait.until(
EC.presence_of_all_elements_located((By.XPATH,
'.//span[@class="storeCount-txt"]')))

print(stores[0].text)

当我运行这段代码时,输​​出是:

> em 14 lojas

但是,当我在 headless 模式下运行它(删除#s)时,输出为空:

> ""

对正在发生的事情有什么想法吗?

最佳答案

当我运行部署在 Heroku 中并以 headless 模式运行 chrome 的网络抓取脚本时,我遇到了同样的问题。我通过将以下 chrome 选项添加到我的选项列表中解决了这个问题

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("--window-size=1920x1080") #I added this

正如您问题中的评论所提到的,可能有两件事可能导致某些元素不显示

  1. 您所在的分辨率不显示我通过添加该选项解决的元素(或类似的内容)
  2. 您正在搜索尚未加载的元素。我建议适当等待(您已经使用stores变量完成了),您也可以使用它来代替

     try:
    # Wait until 'what you specified' is visible
    WebDriverWait(driver, 60) \
    .until(expected_conditions.visibility_of_element_located((By.XPATH, './/span[@class="storeCount-txt"]')))
    except Exception as exp:
    print("Exception occured", exp)
    driver.quit()

希望这有帮助

关于python - Selenium Chrome 获取文本在 headless 模式下不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54486265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com