我有一个python爬虫,它使用phanthomjs来抓取网站,我试图停止从这些网页加载'css'的内容,但这不起作用。请帮助我解决这个问题。我也尝试了堆栈溢出中提到的其他解决方案,但也没有奏效。在
driver = webdriver.PhantomJS()
driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')
driver.execute('executePhantomScript', {'script': '''
var page = this;
page.onResourceRequested = function(requestData, request) {
if ((/http:\/\/.+?\.css/gi).test(requestData['https://www.whatismyip.com/']) || requestData.headers['Content-Type'] == 'text/css') {
console.log('The url of the request is matching. Aborting: ' + requestData['https://www.whatismyip.com/']);
request.abort();
}
''', 'args': []})
driver.get("https://www.whatismyip.com/")
ipaddress=driver.find_element_by_xpath("//div[@class='ip']").text
print ipaddress
driver.quit()
您正在针对
requestData['https://www.whatsmyip.com/']
测试regex,我假设是null
,这是通过使用requestData.url
按照the documentation来修复的。另外,请求将不包含Content-Type
,因此可以删除此条件。在我选择简化您的正则表达式,因为有些url可能使用SSL或relative提供服务,并且与
http://
不匹配。我将使用一个$
锚点来测试URL末尾的.css
(不需要使用g
全局修饰符,因为您只查找一个匹配项)。在最后的
.onResourceRequested
回调可能包含如下条件:相关问题 更多 >
编程相关推荐