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

标签 python selenium selenium-chromedriver

当我使用 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/

相关文章:

python - 无法解析功能 : goog:chromeOptions from invalid argument: unrecognized chrome option: prefs

selenium - 使用 Selenium ChromeDriver ChromeOptions 清除缓存

python - 在 Python 中使用 glob.glob 和正则表达式与 unicode 文件名的文件系统独立方式

python - 使用 2 个坐标选择数组中的项目并填充它

python - 添加不同索引的列

java - 在 Hudson 中通过 JUnit 运行 Selenium 测试

python - 如何更新覆盖率(包含在 pybuilder 中)以忽略 run.py 模块?

Google map 的 Selen 测试

java - 为不同的测试重用相同的网络驱动程序,但不是每次都实例化它

java - CreatePlatformSocket() 返回错误 : An invalid argument was supplied. 端口不可用。在 Chrome 上运行 selenium 代码时退出...