【发布时间】:2018-07-16 02:48:59
【问题描述】:
我正在尝试在 chrome 中读取开发人员工具的网络和控制台选项卡或与之交互。请指导我如何实现这一目标。
谢谢
【问题讨论】:
-
查看我的帖子:medium.com/@ohanaadi/…
标签: selenium
我正在尝试在 chrome 中读取开发人员工具的网络和控制台选项卡或与之交互。请指导我如何实现这一目标。
谢谢
【问题讨论】:
标签: selenium
简短的回答是否定的。 How to open Chrome Developer console in Selenium WebDriver using JAVA。正如提供的链接所述,您无法直接访问 chrome 开发人员工具。
但如果您有兴趣访问浏览器控制台和网络选项卡的内容,selenium 为您提供了一种方式。
System.setProperty("webdriver.chrome.driver", getChromeDriverLocation());
LoggingPreferences loggingprefs = new LoggingPreferences();
loggingprefs.enable(LogType.BROWSER, Level.WARNING);
loggingprefs.enable(LogType.PERFORMANCE, Level.WARNING);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(CapabilityType.LOGGING_PREFS, loggingprefs);
driver = new ChromeDriver(capabilities);
然后您可以根据需要打印日志
LogEntries logEntries = SeleniumBaseTest.getWebDriver().manage().logs()
.get(org.openqa.selenium.logging.LogType.BROWSER);
for (LogEntry entry : logEntries) {
System.out.println((String.format("%s %s %s\n", new Date(entry.getTimestamp()), entry.getLevel(),
entry.getMessage())));
}
LogType.BROWSER 会给你browser console。
Logtype.PERFROMANCE 会给你network tab。
访问网络选项卡的其他方法是使用浏览器代理记录交易。 http://www.seleniumeasy.com/selenium-tutorials/browsermob-proxy-selenium-example
【讨论】:
在 Python 中,Pychrome 作为 DevTools 协议查看器的接口可以正常工作。
下面是一个示例,我将 Selenium 用于主要请求和 Pychrome,因为我想在不下载两次的情况下获取图像...
import base64
import pychrome
def save_image(file_content, file_name):
try:
file_content=base64.b64decode(file_content)
with open("C:\\Crawler\\temp\\" + file_name,"wb") as f:
f.write(file_content)
except Exception as e:
print(str(e))
def response_received(requestId, loaderId, timestamp, type, response, frameId):
if type == 'Image':
url = response.get('url')
print(f"Image loaded: {url}")
response_body = tab.Network.getResponseBody(requestId=requestId)
file_name = url.split('/')[-1].split('?')[0]
if file_name:
save_image(response_body['body'], file_name)
tab.Network.responseReceived = response_received
# start the tab
tab.start()
# call method
tab.Network.enable()
# get request to target the site selenium
driver.get("https://www.realtor.com/ads/forsale/TMAI112283AAAA")
# wait for loading
tab.wait(50)
【讨论】: